以下函数实现两个复杂对象(数组和对象相互嵌套)比较,并返回差异部分。
功能已经实现,感觉代码写得有些冗余,请各位大佬指正。
[JavaScript] 纯文本查看 复制代码 function funDifference(object, other) {
let diff = {};
let vChildren;
for (var key in object) {
if (Object.prototype.toString.call(object[key]) === '[object Object]' && Object.prototype.toString.call(other[key]) === '[object Object]' && object[key] && other[key]) {
vChildren = funDifference(object[key], other[key]);
if (Object.keys(vChildren).length > 0) {
diff[key] = vChildren;
}
} else if (Object.prototype.toString.call(object[key]) === '[object Array]' && Object.prototype.toString.call(other[key]) === '[object Array]' && object[key] && other[key]) {
$.each(object[key], function (i, v) {
if (typeof v === "object") {
vChildren = funDifference(object[key], other[key]);
if (Object.keys(vChildren).length > 0) {
diff[key] = vChildren[0];
}
} else if (JSON.stringify(object[key].sort()) !== JSON.stringify(other[key].sort())) {
diff[key] = object[key];
}
})
} else if (object[key] !== other[key]) {
diff[key] = object[key];
}
}
return diff;
}
var object = {firstname: ['John','kks'], lastname: 'Cena',tel: '33',privateInfo: {privateProperty1: "false", privateProperty2: [{oo:"sd",aa:[{yy:'88',ll:'3s3'}]}]}};
var other = {firstname: ['John','kk'], lastname: 'Cena', tel: '44',privateInfo: {privateProperty1: "true", privateProperty2: [{oo:"sd",aa:[{yy:'88',ll:'33'}]}]}};
console.log(JSON.stringify(funDifference(object, other)));
输出:
[JavaScript] 纯文本查看 复制代码 {"firstname":["John","kks"],"tel":"33","privateInfo":{"privateProperty1":"false","privateProperty2":{"aa":{"ll":"3s3"}}}} |