The typical way of creating a Javascript object is the following:
var map = new Object();
map[myKey1] = myObj1;
map[myKey2] = myObj2;
I need to create such a map where both keys and values are Strings. I have a large but static set of pairs to add to the map.
Is there any way to perform something like this in Javascript:
var map = { { "aaa", "rrr" }, { "bbb", "ppp" } ... };
or do I have to perform something like this for each entry:
map["aaa"]="rrr";
map["bbb"]="ppp";
...
Basically, remaining Javascript code will loop over this map and extract values according to criterias known 'at runtime'. If there is a better data structure for this looping job, I am interested too. My objective is to minimize code.
It works fine with the object literal notation:
Btw, the common way to instantiate arrays
and objects
Also you can do either:
Give this a try:
JavaScript's object literal syntax, which is typically used to instantiate objects (seriously, no one uses
new Object
ornew Array
), is as follows:For arrays it's:
If you need objects within objects, that's fine too:
This convenient method of being able to instantiate static data is what led to the JSON data format.
JSON is a little more picky, keys must be enclosed in double-quotes, as well as string values:
In ES2015 a.k.a ES6 version of JavaScript, a new datatype called
Map
is introduced.check this reference for more info.
The syntax you wrote as first is not valid. You can achieve something using the follow: