简体   繁体   中英

How can I compare two objects and remove duplicates?

For example:

let oldData = {user1: {name:'Felix', balance:1000},
                  user2: {name:'Marques', balance:3000}}
let newData = {user1: {name:'Felix', balance:1000},
                  user2: {name:'Marques', balance:2000}}

The only thing that changed is user2's balance so how can I get a output like:

{user2: {balance:2000}}

Since the objects you want to compare have some depth (inner objects) you can cycle through recursively and build up the differences. The code below seems to do the job.

 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM