我将给出两个对象的简化版,其中包含嵌套对象:
对象1:
{firstname: 'John', lastname: 'Cena', privateInfo: {privateProperty1: false, privateProperty2: true}}
Object2:
{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。效率在这里很重要。
答案 0 :(得分:1)
只需遍历对象键并将它们与另一个对象进行比较。由于可能存在嵌套对象,因此需要递归:
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));
注意:如果嵌套对象相同,则它们的区别将是一个空对象,这是合乎逻辑的。