1

Because my code will need to run this a lot, I need a very fast code to get the difference between 2 objects. Deleted properties should have a value of "deleted".

Example:

Object 1

{a: "hi", b: "hi", c: {o: "hi", p: "hi",}, d: ["hi", "bye"]}

Object 2

{a: "hi", b: "bye", c: {o: "bye",}, e: "new"}

Result

{b: "bye", c: {o: "bye", p: "deleted"}, d: "deleted", e: "new"}
hmmmm
  • 23
  • 4

1 Answers1

2

You could use some recursive function to handle objects. It's not clear whether you need to handle arrays too

const old = {a: "hi", b: "hi", c: {o: "hi", p: "hi",}, d: ["hi", "bye"]}
const cur = {a: "hi", b: "bye", c: {o: "bye", f: "new"}, e: "new"};

const diff = (old, cur, result = {}) => {

  for(const k in cur){
    if(Object.is(old[k], cur[k])){
      continue;
    }
    if(cur[k].__proto__ === Object.prototype){
        diff(old[k], cur[k], result[k] = {});  
    }else{
      result[k] = cur[k];
    }
  }
  for(const k in old){
    if(!(k in cur)){
      result[k] = 'deleted';
    }
  }
  return result;

};



console.log(diff(old, cur));
Alexander Nenashev
  • 8,775
  • 2
  • 6
  • 17