xuanji xuanji - 7 months ago 46
Javascript Question

Map over object preserving keys

The

map
function in underscore.js, if called with a javascript object, returns an array of values mapped from the object's values.

_.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; });
=> [3, 6, 9]


is there a way to make it preserve the keys? ie, I want a function that returns

{one: 3, two: 6, three: 9}

GG. GG.
Answer

Underscore provides a function _.object to convert an array into an object.

_.object(_.map({ one: 1, two: 2, three: 3 }, function (num, key) {
    return [key, num * 3];
}));

=> {one: 3, two: 6, three: 9}

DEMO

Comments