react – function to return the changes of object

Let’s assume I have below object

let obj = {
    id:1,
    likes: 20,
    createdBy: 'tom'
}

Then I create new object which is used to record the changes.

let dynamicObject = obj;
obj.likes = 30;
createdBy = 'ken';

// which should be
//  {
//     id:1,
//     likes: 30,
//     createdBy: 'ken'
//  }

I want to create a function like below, so as to get the changes of the object for my PATCH request.

someFunc(obj, dynamicObject)

which return

 {
    likes: 30,
    createdBy: 'ken'
 }

Is there any library or method to do it?

Answer

You can use a deep equality function with a small modification, like this:

const diffObjects = (x, y, z) => {
  if (x === y) return {};
  if (!(x instanceof Object) || !(y instanceof Object)) return 'ALL';
  if (x.constructor !== y.constructor) return 'ALL';
  for (var p in x) {
    if (!x.hasOwnProperty(p)) continue;
    if (!y.hasOwnProperty(p)) {
      z[p] = x[p];
      continue;
    }
    if (x[p] === y[p]) continue;
    if (typeof (x[p]) !== 'object') {
      z[p] = y[p];
      continue;
    }
    const z1 = {};
    diffObjects(x[p], y[p], z1);
    if (JSON.stringify(z1) !== '{}') { z[p] = z1; }
  }
  for (p in y) { if (y.hasOwnProperty(p) && !x.hasOwnProperty(p)) z[p] = y[p]; }
  return z;
};

console.log(diffObjects(obj1, obj2, {}));