Is there any way to map keys and values in an array using Javascript? In my opinion, it is something similar to jQuery .map()
, but instead of mapping only the value, also "maps" the keys.
Suppose I have the following array:
var names = [ 1, 2, 3, 4, 5 ];
And I like to use a function called numberToName()
that I created and generate another array from this, and the result should be something like this:
var names = { "one": 1, "two": 2, "three": 3, "four": 4, "five": 5 };
Currently I use the 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: is there any way (preferably native) to improve this method? I could even use jQuery without problems. Perhaps a function similar to this:
var names = jQuery.mapKeys([ 1, 2, 3, 4, 5], function(k, v) {
return { key: numberToName(v), value: v };
});
Is there any way to map keys and values in an array using Javascript? In my opinion, it is something similar to jQuery .map()
, but instead of mapping only the value, also "maps" the keys.
Suppose I have the following array:
var names = [ 1, 2, 3, 4, 5 ];
And I like to use a function called numberToName()
that I created and generate another array from this, and the result should be something like this:
var names = { "one": 1, "two": 2, "three": 3, "four": 4, "five": 5 };
Currently I use the 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: is there any way (preferably native) to improve this method? I could even use jQuery without problems. Perhaps a function similar to this:
var names = jQuery.mapKeys([ 1, 2, 3, 4, 5], function(k, v) {
return { key: numberToName(v), value: v };
});
Share
Improve this question
asked Jul 31, 2013 at 21:08
David RodriguesDavid Rodrigues
12.6k17 gold badges66 silver badges94 bronze badges
2 Answers
Reset to default 5You're looking for reduce
:
var names = [1, 2, 3, 4, 5].reduce(function(obj, k) {
return obj[numberToName(k)] = k, obj;
}, {});
return obj[numberToName(k)] = k, obj
is a shorthand (and admittedly less readable) way to write assignment + return:
obj[numberToName(k)] = k;
return obj;
A simple forEach
will do the job too:
names = {};
[1, 2, 3, 4, 5].forEach(function(k) {
names[numberToName(k)] = k
})
You can also use jquery's $.each
in the same way if you want.
sure is, (as of IE9):
var nums={};
[ 1, 2, 3, 4, 5].forEach(function(v, i) {
this[numberToName(v)]=v;
}, nums);
nums;
EDIT: added an index to make it easier to tell what's going on.
EDIT: made it perfect by using forEach, which even though it's not as close to $'s .map(), does run about 3% faster than [].map. (thanks to thg435 for the tip!)