3

Currently, I am creating a 3d array in js using the following:

var arr = [["name1", "place1", "data1"],
          ["name2", "place2", "data2"],
          ["name3", "place3", "data3"]];

I can access each element using arr[0] or arr[1]. But is there anyways I can access them using a key like this: arr["name1"] should give me the first one. Any suggestions? I think I am looking for a Hashmap like functionality.

Legend
  • 109,064
  • 113
  • 265
  • 394

3 Answers3

3

The only way you could do that is by wrapping it in an object.

var arr = {
    name1 : ["name1", "place1", "data1"],
    name2 : ["name2", "place2", "data2"],
    name3 : ["name3", "place3", "data3"]
};
ChaosPandion
  • 75,687
  • 16
  • 116
  • 154
1

Javascript is a prototype based dynamic language. You can create objects and change their structure when you want.

var o = {name1: {place1: data1}, name2: {place2: data2}};

and access it with:

o.name1

The look-up implementation varies though and when you have a lot of properties that often changes this can be pretty slow (except in Chrome that uses a special scheme to access object properties i.e. embedded classes a-la-dynamic dispatch from smalltalk). Some libraries (e.g. MooTools) provide some hash map related structures,

Matt
  • 72,564
  • 26
  • 147
  • 178
  • So in this example, to access place1, would you reference it with `o.name1.place1`? and what would that give you? The value `place1` or the value `data1`? – Noble-Surfer Mar 13 '13 at 10:06
1

The situation has changed in the six years since this question was asked.

Due to weak typing associative arrays can be faked in JavaScript:

>> var names = new Array();
undefined

>> names["first"] = "Dotan";
"Dotan"

>> names["last"] = "Cohen";
"Cohen"

>> for ( key in names ) { console.log(key+" "+names[key]) }
undefined
first Dotan
last Cohen

That is sometimes useful, and all browsers released since 2012 support it, but there are caveats! The array cannot be simply read back:

>> names
Array [  ]

More importantly, the array's length cannot be easily retrieved:

>> names.length
0

Therefore this is not an associative array in the sense that JavaScript would have supported it had it been intended, but rather a workaround that is often useful if for whatever reason a real JS object does not support what you need:

>> var names = {};
undefined

>> names.first = "Dotan";
"Dotan"

>> names.last = "Cohen";
"Cohen"

>> for ( key in names ) { console.log(key+" "+names[key]) }
undefined
first Dotan
last Cohen

>> names
Object { first: "Dotan", last: "Cohen" }

>> Object.keys(names).length
2
dotancohen
  • 27,834
  • 33
  • 133
  • 191