Underscore.js has a very useful map function.
_.map([1, 2, 3], function(num){ return num * 3; });
=> [3, 6, 9]
_.map({one: 1, two: 2, three: 3
Here is a clean ES6 version:
function mapObject(obj, fn) {
return Object.keys(obj).reduce(
(res, key) => {
res[key] = fn(obj[key]);
return res;
},
{}
)
}
function deepMap(obj, fn) {
const deepMapper = val => typeof val === 'object' ? deepMap(val, fn) : fn(val);
if (Array.isArray(obj)) {
return obj.map(deepMapper);
}
if (typeof obj === 'object') {
return mapObject(obj, deepMapper);
}
return obj;
}