jquery - Mapping key/value with javascript -


is there way map keys , values ​​in array using javascript? in opinion, similar jquery .map(), instead of mapping value, "maps" keys.

suppose have following array:

var names = [ 1, 2, 3, 4, 5 ]; 

and use function called numbertoname() created , generate array this, , result should this:

var names = { "one": 1, "two": 2, "three": 3, "four": 4, "five": 5 }; 

currently use following method:

var names = [ 1, 2, 3, 4, 5 ],     names_tmp = {},     names_i = 0,     names_len = names.length;  for(; names_i < names_len; names_i++) {     names_tmp[numbertoname(names[names_i])] = names[names_i]; } 

the question is: there way (preferably native) improve method? use jquery without problems. perhaps function similar this:

var names = jquery.mapkeys([ 1, 2, 3, 4, 5], function(k, v) {     return { key: numbertoname(v), value: v }; }); 

you're looking reduce:

var names = [1, 2, 3, 4, 5].reduce(function(obj, k) {      return obj[numbertoname(k)] = k, obj; }, {}); 

return obj[numbertoname(k)] = k, obj shorthand (and admittedly less readable) way write assignment + return:

     obj[numbertoname(k)] = k;      return obj; 

a simple foreach job too:

names = {}; [1, 2, 3, 4, 5].foreach(function(k) {    names[numbertoname(k)] = k }) 

you can use jquery's $.each in same way if want.


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -