32

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MxLDevs
  • 19,048
  • 36
  • 123
  • 194

5 Answers5

41

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"
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • you declared an object not array! – Suhayb Apr 25 '17 at 09:59
  • @SuhaybKharabsheh ?? Right? JavaScript arrays should not be used when you want non-numeric property names (unless you have a really good reason). – Pointy Apr 25 '17 at 12:15
  • How do the two approaches scale (say to 10,000 or 1,000,000 elements)? E.g. for insertion and lookup? Is there any difference? E.g. [quadratic behavior](https://www.joelonsoftware.com/2001/12/11/back-to-basics/) would put on a (practical) upper limit on the number of elements. – Peter Mortensen Jul 21 '20 at 21:19
  • @PeterMortensen well property lookup and more generally management in plain JavaScript objects is, as you might imagine, *highly* optimized. – Pointy Jul 21 '20 at 21:26
8

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]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Greg
  • 33,450
  • 15
  • 93
  • 100
8

It is indeed.

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

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

See this example on jsFiddle

Swaff
  • 13,548
  • 4
  • 26
  • 26
5

Short answer... yes...

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

alert(m.Foo[0]);
alert(m["Foo"][1]);
Jimmy Chandra
  • 6,472
  • 4
  • 26
  • 38
0

You can use Map:

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

console.log(var); // Result is: 'Value'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Santo Boldizar
  • 1,255
  • 14
  • 17