0

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?

CCCC
  • 5,665
  • 4
  • 41
  • 88
  • 2
    You are probably looking into object diff https://stackoverflow.com/questions/8572826/generic-deep-diff-between-two-objects. Btw you are not creating a new object with `dynamicObject = obj`. It's still pass by reference – Murat Karagöz Aug 31 '21 at 06:53
  • @Murat Karagöz yes..it's just an example – CCCC Aug 31 '21 at 06:58

2 Answers2

2

I suggest you to use an external library like immer.

It will make object manipulation easier (especially if used with React) and provides patches feature, from which you can access every diff in a user friendly way.

keul
  • 7,673
  • 20
  • 45
1

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, {}));
Max
  • 1,020
  • 7
  • 13