JS - deep map function
Here's a Lodash solution using transform
function deepMap(obj, iterator, context) { return _.transform(obj, function(result, val, key) { result[key] = _.isObject(val) /*&& !_.isDate(val)*/ ? deepMap(val, iterator, context) : iterator.call(context, val, key, obj); });}_.mixin({ deepMap: deepMap});
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;}
Here's my version - slightly lengthy so I expect it can be shortened, but works with arrays and objects and no external dependencies:
function deepMap(obj, f, ctx) { if (Array.isArray(obj)) { return obj.map(function(val, key) { return (typeof val === 'object') ? deepMap(val, f, ctx) : f.call(ctx, val, key); }); } else if (typeof obj === 'object') { var res = {}; for (var key in obj) { var val = obj[key]; if (typeof val === 'object') { res[key] = deepMap(val, f, ctx); } else { res[key] = f.call(ctx, val, key); } } return res; } else { return obj; }}
demo at http://jsfiddle.net/alnitak/0u96o2np/
EDIT slightly shortened now by using ES5-standard Array.prototype.map
for the array case