Map Values in JavaScript
Although there are a lot of base array manipulation methods in modern JavaScript like reduce, there are not a lot methods to manipulate objects. One of the simplist operations is to transform the values of an object while keeping the keys to reference them. By using a mapValues function, the object maintainance can be reduced and everything can be returned:
var cars = { 'miata': { hp: 155, weight: 2332 }, 'elise': { hp: 217, weight: 2041 }, 'Romeo 4C': { hp: 237, weight: 2456 } }; var getWeightToPower = function(cars) { return mapValues(cars, function(car) { return Math.round(car.weight/car.hp); }); }; console.log(getWeightToPower(cars)); // { miata: 15, elise: 9, 'Romeo 4C': 10 }
And here is the implementation:
var mapValues = function(obj, callback) { // Prevent in-place modification. var newObj = {}; for (var key in obj) { newObj[key] = callback(obj[key]); } return newObj; };
A mapKeys function is less useful, but it has an interesting implementation:
var mapKeys = function(obj, callback) { // Prevent in-place modification. var newObj = {}; for (var key in obj) { newObj[callback(obj[key])] = obj[key]; } return newObj; }; var getWeightToPowerKeys = function(cars) { return mapKeys(cars, function(car) { return Math.round(car.weight/car.hp); }); }; console.log(getWeightToPowerKeys(cars)); // { '9': { hp: 217, weight: 2041 }, // '10': { hp: 237, weight: 2456 }, // '15': { hp: 155, weight: 2332 } }
The callback was just shifted into the key creation. Both mapKeys and mapValues are present in utility libraries like LoDash.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2016/mapValues.js
















