Map over object preserving keys Map over object preserving keys javascript javascript

Map over object preserving keys


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


var mapped = _.reduce({ one: 1, two: 2, three: 3 }, function(obj, val, key) {    obj[key] = val*3;    return obj;}, {});console.log(mapped);
<script src="http://underscorejs.org/underscore-min.js"></script><script src="https://getfirebug.com/firebug-lite-debug.js"></script>