3 回答
TA贡献1821条经验 获得超4个赞
您也可以通过检查嵌套零件来检查零件并获得结果。
function getDifference(a, b) {
return [...new Set([...Object.keys(a), ...Object.keys(b)])].reduce((r, k) => {
if (a[k] && b[k] && typeof a[k] === 'object' && typeof b[k] === 'object') {
var temp = getDifference(a[k], b[k]);
if (temp.length) r.push(...temp.map(([l, ...a]) => [k + ' ' + l, ...a]));
return r;
}
if (k in a && !(k in b)) {
r.push([k, 'deleted', a[k]]);
return r;
}
if (!(k in a) && k in b) {
r.push([k, 'created', b[k]]);
return r;
}
if (a[k] === b[k]) return r;
r.push([k, 'changed', a[k], b[k]]);
return r;
}, []);
}
console.log(getDifference(
{ a: { b: 1, c: 2 }, d: false, e: 15, f: "something important" },
{ a: { b: 1, c: 22 }, d: false, e: "fifteen", g: "something new" }
));
.as-console-wrapper { max-height: 100% !important; top: 0; }
TA贡献1816条经验 获得超4个赞
添加回答
举报