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 };
});