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}
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.
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.
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.
To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With