Home > other >  How to identify changes between objects including null fields
How to identify changes between objects including null fields

Time:08-20

I have the following payload object, which has a current and previous. As you can see, field2 and field3 have changed.

const payload = {
  current: {
    field1 : 1,
    field2 : 22,
    field3 : null,
    field4 : 4  
  },
  previous: {
    field1 : 1,
    field2 : 2,
    field3 : 3,
    field4 : 4   
  }
}

I am using the following to return an object of the differences.

const getDifference = (a, b) => Object.entries(a).reduce((ac, [k, v]) => b[k] && b[k] !== v ? (ac[k] = b[k], ac) : ac, {});

const payload_changelog = getDifference(payload.previous,payload.current)

console.log(payload_changelog)

payload_changelog prints the following

{
  field2 : 22
}

How do I correctly identify the null changes, so as to return:

{
  field2 : 22,
  field3: null
}

CodePudding user response:

It can be done by filtering by entries and then restoring the filtered object, like so:

const payload = {
  current: {
    field1 : 1,
    field2 : 22,
    field3 : null,
    field4 : 4  
  },
  previous: {
    field1 : 1,
    field2 : 2,
    field3 : 3,
    field4 : 4   
  }
};

const filtered = Object.fromEntries(Object.entries(payload.current)
  .filter(function ([field, value]) {
    return this[field] !== value;
}, payload.previous));

console.log(filtered);

  • Related