0

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}}
  • 1
    Does this answer your question? [Javascript JSON comparison/diff?](https://stackoverflow.com/questions/10357830/javascript-json-comparison-diff) – user120242 Jun 26 '20 at 10:34
  • https://stackoverflow.com/questions/22108837/get-the-delta-of-two-javascript-objects?noredirect=1&lq=1 and https://stackoverflow.com/questions/8431651/getting-a-diff-of-two-json-objects?noredirect=1&lq=1 – user120242 Jun 26 '20 at 10:38
  • 2
    Probably a typo but `new` is a keyword and cant be used as object name – Suraj Rao Jun 26 '20 at 11:02

1 Answers1

1

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))
Always Learning
  • 5,510
  • 2
  • 17
  • 34