-2

I'm trying to make a multiple dimensional array but i can't find a way to set both a unique index and value simultaneously, like this in PHP.

$Countries = array(
    "America" => array(
         "Delaware" => array(
             "Population" => "967.171 (2018)", "KM2" => "6.446"
         )
    )
);

And i have tried to do the same in javascript but can't get it to work.

var Countries = [
    "America" => [
        "Delaware" => [
            "Population" => "967.171 (2018)", "KM2" => "6.446"
        ]
    ]
];

I've also tried to replace the => with = : and -> and none of them works either, so am i in a dead end?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 1
    Use JS objects instead: `var Countries = { 'America': { 'Delaware': { 'Population': 'xxx', 'KM2': 'xxx' } } }`. JS arrays can have string indexes but they are not really made for that as their length will not count these. – Kévin Bibollet Jun 17 '19 at 09:26
  • 1
    Why not use `Object` and its properties: `var Countries = [ { name : "America", states : [ {name : "Delaware", population : "967.171 (2018)", KM2 : "6.446"} ]} ];` – shrys Jun 17 '19 at 09:29

3 Answers3

5

You have to use an object instead of an array for this. That way, you can reference them by their unique key:

let countries = {
  "America" : {
    "Delaware" : {
      "population" : "967.171 (2018)",
      "KM2" : "6.446",
    }
  }
};

Now, you can access the properties in this way:

let populationOfDelaware1 = countries.America.Delaware.population;
// OF
let populationOfDelaware2 = countries["America"]["Delaware"]["population"];
Titulum
  • 9,928
  • 11
  • 41
  • 79
5

I've also tried to replace the => with = : and -> and none of them works either, so am i in a dead end?

The closest equivalent to PHP's associative array in JavaScript is an object. You create objects using {}, specifying properties using name: value syntax:

var Countries = {
    "America": {
        "Delaware": {
            "Population": "967.171 (2018)",
            "KM2": "6.446"
        }
    }
};
console.log(Countries);

The name can be in quotes (as above) or, if the name is a valid identifier, without quotes. America, Delaware, Population, and KM2 are all valid JavaScript identifiers and so don't require quotes, but if you wanted a property name like foo bar, you'd need the quotes because of the space.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

Use an object:

var Countries = {
  America: {
    Delaware: {
      Population: ["967.171 (2018)"],
      KM2: "6.446"
    }
  }
};
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79