Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 496
MxLDevs Avatar asked Mar 25 '11 14:03

MxLDevs


People also ask

Does JavaScript have associative array?

JavaScript does not support associative arrays. You should use objects when you want the element names to be strings (text). You should use arrays when you want the element names to be numbers.

How do you write associative array in JavaScript?

An associative array is declared or dynamically createdWe can create it by assigning a literal to a variable. var arr = { "one": 1, "two": 2, "three": 3 }; Unlike simple arrays, we use curly braces instead of square brackets. This has implicitly created a variable of type Object.

What is [] vs {} in JS?

[] is declaring an array. {} is declaring an object. An array has all the features of an object with additional features (you can think of an array like a sub-class of an object) where additional methods and capabilities are added in the Array sub-class.

What is object as associative array in JavaScript?

Associative arrays are basically objects in JavaScript where indexes are replaced by user defined keys. They do not have a length property like normal array and cannot be traversed using normal for loop. Following is the code for associative arrays in JavaScript −


2 Answers

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" 
like image 53
Pointy Avatar answered Sep 29 '22 11:09

Pointy


It is indeed.

var myMap = {london: ['clapham', 'chelsea'], bristol:['clifton', 'redland']}  alert(myMap.london[0]); alert(myMap['bristol'][1]); 

See this example on jsFiddle

like image 25
Swaff Avatar answered Sep 29 '22 10:09

Swaff