First we define an abstract function that applies func to a combination of two objects, and then uses it together with the sum function.
function merge(x, y, fn) {
var result = {};
Object.keys(x).forEach(function(k) {
result[k] = x[k];
});
Object.keys(y).forEach(function(k) {
result[k] = k in x ? fn(x[k], y[k]) : y[k];
});
return result;
}
function add(p, q) {
if(typeof p === 'object' && typeof q === 'object') {
return merge(p, q, add);
}
return p + q;
}
a = { "a" : 1, "b" : 3, "d": {"da": 1}};
b = { "a" : 1, "c" : 34, "d": {"da": 2}};
sum = merge(a, b, add)
document.write('<pre>'+JSON.stringify(sum,0,3));
Run codeHide resultmerge can also be written in a more functional style, for example:
function clone(x) {
return Object.keys(x).reduce(function(res, k) {
res[k] = x[k];
return res;
}, {});
}
function merge(x, y, fn) {
return Object.keys(y).reduce(function(res, k) {
res[k] = k in x ? fn(x[k], y[k]) : y[k];
return res;
}, clone(x));
}
If you are ok with the first object changed, you can skip the step cloneand just go through x.
georg source
share