Friday, 15 January 2010

How to fill a Javascript map with many static key/value pairs efficiently? -



How to fill a Javascript map with many static key/value pairs efficiently? -

the typical way of creating javascript map following:

var map = new object(); map[mykey1] = myobj1; map[mykey2] = myobj2;

i need create such map both keys , values strings. have big static set of pairs add together map.

is there way perform in javascript:

var map = { { "aaa", "rrr" }, { "bbb", "ppp" } ... };

or have perform each entry:

map["aaa"]="rrr"; map["bbb"]="ppp"; ...

basically, remaining javascript code loop on map , extract values according criterias known 'at runtime'. if there improve info construction looping job, interested too. objective minimize code.

javascript's object literal syntax, typically used instantiate objects (seriously, no 1 uses new object or new array), follows:

var obj = { 'key': 'value', 'another key': 'another value', anunquotedkey: 'more value!' };

for arrays it's:

var arr = [ 'value', 'another value', 'even more values' ];

if need objects within objects, that's fine too:

var obj = { 'subobject': { 'key': 'value' }, 'another object': { 'some key': 'some value', 'another key': 'another value', 'an array': [ 'this', 'is', 'ok', 'as', 'well' ] } }

this convenient method of beingness able instantiate static info led json info format.

json little more picky, keys must enclosed in double-quotes, string values:

{"foo":"bar", "keywithintegervalue":123}

javascript map static-initialization

No comments:

Post a Comment