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'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