2

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

2 Answers 2

5

You'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.

Sign up to request clarification or add additional context in comments.

10 Comments

umm, no he's not. that's a bass-ackwards way of pretending reduce is map or foreach...
@dandavis: I see you understood the question and edited your post. I think forEach is better than map here though (if you dislike reduce for some reason).
kill the closure and i'll remove my answer.
@dandavis: let the OP decide.
I think that .reduce() works better for me, because I need return the value as array directly to var. forEach will not do that. Right?
|
1

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!)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.