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
Based on @megawac response, I made some improvements.
function mapExploreDeep(object, iterateeReplace, iterateeExplore = () => true) {
return _.transform(object, (acc, value, key) => {
const replaced = iterateeReplace(value, key, object);
const explore = iterateeExplore(value, key, object);
if (explore !== false && replaced !== null && typeof replaced === 'object') {
acc[key] = mapExploreDeep(replaced, iterateeReplace, iterateeExplore);
} else {
acc[key] = replaced;
}
return acc;
});
}
_.mixin({
mapExploreDeep: mapExploreDeep;
});
This version allows you to replace even objects & array themselves, and specify if you want to explore each objects/arrays encountered using the iterateeExplore
parameter.
See this fiddle for a demo