JS 两个对象的深度比较,并返回不同部分
吾友大家好,有两个JS对象,我希望进行比较,并返回不同的部分,大家有什么好的写法,指教一下,感谢{:301_997:}var array1={a1:"a1的值",a2:"a2val",a3:{b1:"b1val",b2:{c1:"c1的值"}}};
var array2={a1:"a1的第二个值",a2:"a2val1",a3:{b1:"b1val",b2:{c1:"c1的第二个值"}},a4:"a4val"};
//希望比较后返回两个对象不同的部分,例如:{a1:"a1的第二个值",a3:{b2:{c1:"c1的第二个值"}},a4:"a4val"} 不要说了直接遍历 对象判断就行了复杂度又不高 直接遍历不就完事了,非要折腾,可以看看能不能通过set来搞 已解决,分享代码:
function funDifference(object, other) {
let diff = {};
let vChildren;
for (var key in object) {
if (typeof object === "object" && typeof other === "object" && object && other) {
vChildren = funDifference(object, other);
if (Object.keys(vChildren).length > 0) {
diff = vChildren;
}
} else if (object !== other) {
diff = object;
}
}
return diff;
}
页:
[1]