are there dictionaries in javascript like python? are there dictionaries in javascript like python? python python

are there dictionaries in javascript like python?


This is an old post, but I thought I should provide an illustrated answer anyway.

Use javascript's object notation. Like so:

states_dictionary={      "CT":["alex","harry"],      "AK":["liza","alex"],      "TX":["fred", "harry"]};

And to access the values:

states_dictionary.AK[0] //which is liza

or you can use javascript literal object notation, whereby the keys not require to be in quotes:

states_dictionary={      CT:["alex","harry"],      AK:["liza","alex"],      TX:["fred", "harry"]};


There were no real associative arrays in Javascript until 2015 (release of ECMAScript 6). Since then you can use the Map object as Robocat states. Look up the details in MDN. Example:

let map = new Map();map.set('key', {'value1', 'value2'});let values = map.get('key');

Without support for ES6 you can try using objects:

var x = new Object();x["Key"] = "Value";

However with objects it is not possible to use typical array properties or methods like array.length. At least it is possible to access the "object-array" in a for-in-loop.


I realize this is an old question, but it pops up in Google when you search for 'javascript dictionaries', so I'd like to add to the above answers that in ECMAScript 6, the official Map object has been introduced, which is a dictionary implementation:

var dict = new Map();dict.set("foo", "bar");//returns "bar"dict.get("foo");

Unlike javascript's normal objects, it allows any object as a key:

var foo = {};var bar = {};var dict = new Map();dict.set(foo, "Foo");dict.set(bar, "Bar");//returns "Bar"dict.get(bar);//returns "Foo"dict.get(foo);//returns undefined, as {} !== foo and {} !== bardict.get({});