To generate one object from another, people will frequently use reduce
:
var a = {a: {c: 1}, b: 2};
var m = function n(o) {
return Object.keys(o).reduce(function(newObj, key) {
var value = o[key];
if (value !== null && typeof value === 'object') {
newObj[key] = n(value);
} else {
newObj[key] = value * 5;
}
return newObj;
}, {});
};
console.log(m(a));
We pass in a new object as the "accumulator" and set properties on it, returning it from the reduce
callback each time so it passes through the entire process.
This is sometimes called an "abusage" of reduce
, since the value of the accumulator never changes (it's always the same object; the object's state changes, but not the object), whereas normally the reduce
callback alters the value passing through it.
If you prefer, forEach
closing over the new object is the other common way:
var a = {a: {c: 1}, b: 2};
var m = function n(o) {
var newObj = {};
Object.keys(o).forEach(function(key) {
var value = o[key];
if (value !== null && typeof value === 'object') {
newObj[key] = n(value);
} else {
newObj[key] = value * 5;
}
});
return newObj;
};
console.log(m(a));