我将给出我的两个对象的简化版本,其中包含嵌套对象:
对象 1:
{firstname: 'John', lastname: 'Cena', privateInfo: {privateProperty1: false, privateProperty2: true}}
对象 2:
{firstname: 'John', middlename: 'Felix', lastname: 'Pina', privateInfo: {privateProperty1: true, privateProperty2: true} }
将 Object1 与 Object2 进行比较后,我想将 Object2 具有的所有不同属性存储在新对象中。就我而言,这将是:
let Object3 = {middlename: 'Felix', lastname: 'Pina', privateInfo: {privateProperty1: true}}
比较这些对象的所有属性(包括嵌套对象和缺失对象(的最佳和最有效的方法是什么?
在我的情况下,对象的属性可以达到 30-40。效率在这里非常重要。
只需循环访问对象键并将它们与其他对象进行比较即可。由于可能存在嵌套对象,因此需要递归:
function difference(object, other) {
var diff = {};
for(var key in object) {
if(typeof object[key] === "object" && typeof other[key] === "object" && object[key] && other[key]) {
diff[key] = difference(object[key], other[key]);
} else if(object[key] !== other[key]) {
diff[key] = object[key];
}
}
return diff;
}
例:
function difference(object, other) {
var diff = {};
for(var key in object) {
if(typeof object[key] === "object" && typeof other[key] === "object" && object[key] && other[key]) {
diff[key] = difference(object[key], other[key]);
} else if(object[key] !== other[key]) {
diff[key] = object[key];
}
}
return diff;
}
var object1 = {firstname: 'John', lastname: 'Cena', privateInfo: {privateProperty1: false, privateProperty2: true}};
var object2 = {firstname: 'John', middlename: 'Felix', lastname: 'Pina', privateInfo: {privateProperty1: true, privateProperty2: true} };
console.log(difference(object2, object1));
注意:如果嵌套对象相同,则它们的差异将是空对象,这是合乎逻辑的。