如何合并两个只有唯一或不同值的复杂JSON对象,这些值只显示在结果数组中

How can I merge two complex JSON objects with only unique or different values only showing in resultant array

本文关键字:JSON 复杂 对象 显示 数组 结果 合并 何合并 两个 唯一      更新时间:2023-09-26

如果我有两个复杂的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"}
}

根据Markus对这个问题的回答,我能够解决这个问题:如何动态合并两个JavaScript对象的属性?

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;
}

根据您喜欢的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);
}