Sunday, May 19, 2024
74
rated 0 times [  80] [ 6]  / answers: 1 / hits: 149334  / 11 Years ago, thu, september 26, 2013, 12:00:00

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}

More From » underscore.js

 Answers
7

With Underscore



Underscore provides a function _.mapObject to map the values and preserve the keys.



_.mapObject({ one: 1, two: 2, three: 3 }, function (v) { return v * 3; });

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


DEMO






With Lodash



Lodash provides a function _.mapValues to map the values and preserve the keys.



_.mapValues({ one: 1, two: 2, three: 3 }, function (v) { return v * 3; });

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


DEMO


[#75415] Wednesday, September 25, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jensenb

Total Points: 634
Total Questions: 102
Total Answers: 102

Location: Bosnia and Herzegovina
Member since Thu, Jun 24, 2021
3 Years ago
;