如果我有两个复杂的JSON对象,如:
{
"name": "foo",
"class": "top",
"plop": {"class4": "A", "class3": "C", "class2": "B"}
}
和
{
"name": "foo",
"clank": "poop",
"class": "flop",
"plop": {"class4": "A", "class3": "A", "class2": "B"}
}
我如何合并它们,以便在结果对象中只有唯一或不同的值?像这样:
{
"clank": "poop",
"class": "flop",
"plop": {"class3": "A"}
}
答案 0 :(得分:2)
根据Markus对这个问题的回答,我能够解决这个问题: How can I merge properties of two JavaScript objects dynamically?
function MergeRecursiveDiff(obj1, obj2) {
for (var p in obj2) {
try {
// Property in destination object set; update its value.
if ( obj2[p].constructor==Object ) {
obj1[p] = MergeRecursiveDiff(obj1[p], obj2[p]);
} else {
//Here, I test if the objects are already the same
if(obj1[p] === obj2[p]) {
//If they're the same, I delete the first object
delete(obj1[p]);
} else {
obj1[p] = obj2[p];
}
}
} catch(e) {
// Property in destination object not set; create it and set its value.
obj1[p] = obj2[p];
}
}
return obj1;
}
答案 1 :(得分:1)
根据您首选的JS编程风格,以下内容可能被认为是紧凑且可读的:
function find_diff(o1, o2) {
// determine if something is a non-null object
function is_object(o) { return typeof o === 'object' && o; }
// handle case where objects are equal or either is undefined
if (o1===o2 || o1===undefined && o2===undefined) { return undefined; }
if (o1===undefined) { return o2; }
if (o2===undefined) { return o1; }
// implement semantics that second value "wins"
if (!is_object(o1) || !is_object(o2)) { return o2; }
// iterate over combined set of keys, constructing a resulting object of diffs
return Object.keys(o1).concat(Object.keys(o2)).reduce(function(result, key) {
var val1 = o1[key], val2 = o2[key];
// find resulting value for this key, based on its presence on one side only,
// or diff of both values
var ret = key in o1 ? key in o2 ? find_diff(val1, val2) : val1 : val2;
// if there is a meaningful (non-undefined) diff, add to result
if (ret !== undefined) {
result = result || {};
result[key] = ret;
}
return result;
}, undefined);
}