MxLDevs
MxLDevs

Reputation: 19506

JavaScript associate array

In Python I could do something like myMap = {key: [value1, value2]} and then access the value2 using myMap[key][1]

Can I do something like this in JavaScript?

Upvotes: 32

Views: 49882

Answers (5)

Santo Boldizar
Santo Boldizar

Reputation: 1395

You can use Map:

var myMap = new Map();
myMap.set('key','Value');
var res = myMap.get('key');

console.log(var); // Result is: 'Value'

Upvotes: 0

Greg
Greg

Reputation: 33650

Yes, and the syntax is almost the same too.

var myMap = {key: ["value1", "value2"]};
alert(myMap["key"][1]); // Pops up an alert with the word "value2"

You can also use the following notation:

myMap.key[1]

Upvotes: 8

Pointy
Pointy

Reputation: 413720

Well, you can do this:

var myMap = { key: [ value1, value2 ] };
var array = myMap.key; // or myMap["key"]

JavaScript doesn't have an "associative array" type, one that combines "map" behavior with array behavior like keeping track of the number of properties. Thus the common thing to do is use a plain object. In modern JavaScript now (2017), there's an explicit Map facility that allows keys to be of any type, not just strings as when using simple objects.

JavaScript is a little bit silly about the object literal notation, in that it won't let you use reserved words for keys unless you quote them:

var myMap = { 'function': 'hello world' };

The quote syntax allows any string to be used as a property name. To access such properties, you'd use the [ ] operator

console.log(myMap["function"]); // "hello world"

Upvotes: 41

Swaff
Swaff

Reputation: 13621

It is indeed.

var myMap = {london: ['clapham', 'chelsea'], bristol:['clifton', 'redland']}

alert(myMap.london[0]);
alert(myMap['bristol'][1]);

See this example on jsFiddle

Upvotes: 8

Jimmy Chandra
Jimmy Chandra

Reputation: 6580

Short answer... yes...

var m = { Foo : ["Bar", "Baz"] };

alert(m.Foo[0]);
alert(m["Foo"][1]);

Upvotes: 5

Related Questions