比较两个对象以覆盖其中一个对象的值

Compare two object to override values of one of them

本文关键字:覆盖 一个对象 对象 两个 比较      更新时间:2023-09-26

我需要比较两个相同的对象(第二个对象比另一个对象多一个属性)。

我创建了这个代码片段,它将一个对象的所有属性放入一个新对象中,而不嵌套它们:

function getAllObjectProperties(source) {
  var result = {};
  function getProperties(object) {
    for (var property in object) {
      if (typeof object[property] === 'object') getProperties(object[property]); 
      else result[property] = object[property];
    }
  }
  getProperties(source);
  return result;
}

比较函数应该像这样:

updateObjectProperties: function(source, target) {
    var temp_object = self.getAllObjectProperties(source);
    for (var property in temp_object) {
        if (target.hasOwnProperty(property)) {
            // target_property_of_target_element = temp_object[property];
        }
        else {
            // target_object gains new property (property nesting must be preserved)
        }
    }
}

我该怎么办?这可能吗?

可以合并对象。如果只希望在特定条件下合并对象,可以添加条件操作符。

研究这个答案:如何动态合并两个JavaScript对象的属性?

代码:

  var mergeObj =  function (obj1, obj2) {
    var obj3 = {};
    for (var attrname in obj1) {
        obj3[attrname] = obj1[attrname];
    }
    for (var attrname in obj2) {
        obj3[attrname] = obj2[attrname];
    }
    return obj3;
}

JS小提琴https://jsfiddle.net/chrislewispac/8fthog46/

当您将一个对象的属性复制到另一个对象时,您可以使用称为深复制或浅复制的东西。在浅拷贝中,目标对象将引用源对象的属性,这意味着目标对象的更改将会更改源对象。

下面是一个浅拷贝的例子:

var source = {a: 0, b: {c: 2, d: 3}},
    target = {a: 1};
function union(target, source) {
    Object.keys(source).filter(function (key) {
        return !target.hasOwnProperty(key);
    }).forEach(function (key) {
        target[key] = source[key];
    });
}
union(target, source);
console.log(target);

可以使用JSON进行深度复制,但只有在属性可以用JSON表示的情况下才有效。下面是执行深度复制的联合函数。

function union(target, source) {
    Object.keys(source).filter(function (key) {
        return !target.hasOwnProperty(key);
    }).forEach(function (key) {
        target[key] = JSON.parse(JSON.stringify(source[key]));
    });
}