tags:

views:

44

answers:

2

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.

+3  A: 

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
Awesome... Works like a charm. Many thanks!
Legend
@Legend - Don't forget to accept an answer. It will make sure you keep getting quality answers in the future. *Plus it makes me look good. :)*
ChaosPandion
@ChaosPandion: Of course... There's a 15 minute time limit to accept answers :)
Legend
@Legend - Oops. My mistake.
ChaosPandion
+1  A: 

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,

Alexandre Abreu
@Alexandre Abreu: +1 for the pointers. :)
Legend