Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}
like image 291
xuanji Avatar asked Oct 10 '22 14:10

xuanji


People also ask

How do you compare object and Map?

Few basic differences are as follows: In Object, the data-type of the key-field is restricted to integer, strings, and symbols. Whereas in Map, the key-field can be of any data-type (integer, an array, even an object!) In the Map, the original order of elements is preserved.

What is Map () in JavaScript?

Definition and Usage. map() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements. map() does not change the original array.

How do I get all the keys of an object?

For getting all of the keys of an Object you can use Object. keys() . Object. keys() takes an object as an argument and returns an array of all the keys.

How do you turn an object into an array?

To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .


2 Answers

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

like image 125
GG. Avatar answered Oct 14 '22 06:10

GG.


I managed to find the required function in lodash, a utility library similar to underscore.

http://lodash.com/docs#mapValues

_.mapValues(object, [callback=identity], [thisArg])

Creates an object with the same keys as object and values generated by running each own enumerable property of object through the callback. The callback is bound to thisArg and invoked with three arguments; (value, key, object).

like image 26
xuanji Avatar answered Oct 14 '22 04:10

xuanji