【问题标题】:How can I compare two objects and remove duplicates?如何比较两个对象并删除重复项?
【发布时间】:2020-10-16 22:32:56
【问题描述】:
例如:
let old = {user1: {name:'Felix', balance:1000},
user2: {name:'Marques', balance:3000}}
let new = {user1: {name:'Felix', balance:1000},
user2: {name:'Marques', balance:2000}}
唯一改变的是 user2 的余额,所以我怎样才能得到这样的输出:
{user2: {balance:2000}}
【问题讨论】:
标签:
javascript
node.js
json
for-loop
object
【解决方案1】:
由于您要比较的对象具有一定的深度(内部对象),您可以递归循环并建立差异。下面的代码似乎可以完成这项工作。
let old = {user1: {name:'Felix', balance:1000},
user2: {name:'Marques', balance:3000, missing: 7}}
let newer = {user1: {name:'Felix', balance:1000},
user2: {name:'Marques', balance:2000, extra: 7}}
const findDiff = (o1, o2) => {
let diff;
for (const key in o1) {
const obj1 = o1[key]
const obj2 = o2 === undefined? o2 : o2[key]
if (typeof obj1 === 'object') {
// recursively call if it's an object
// unless we know it's undefined in o2 already
if (obj2 === undefined) diff[key] = obj2
else {
const subDiff = findDiff(obj1,obj2)
// if there's a difference, add it to the diff object
if (subDiff !== undefined) {
if (!diff) diff = {}
diff[key] = subDiff
}
}
} else if (obj1 !== obj2) {
// for non-objects add to the diff object if different
diff = {[key]: obj2}
}
}
for (const key in o2) {
// any keys in o2 that weren't in o1 are also differences
if (!o1.hasOwnProperty(key)) {
if (!diff) diff = {}
diff[key] = o2[key]
}
}
return diff
}
console.log(findDiff(old,newer))