diff between two objects in javascript

In JavaScript, we can compare two objects and check if they are equal or not. There are different ways to compare objects, but one common approach is to compare their properties one by one.

Here is an example function that compares two objects and returns an object containing the differences:

index.tsx
function diffObjects(obj1, obj2) {
  const keys = Object.keys({...obj1, ...obj2});

  const differences = {};

  for(let i = 0; i < keys.length; i++) {
    const key = keys[i];

    if(!isEqual(obj1[key], obj2[key])) {
      differences[key] = {
        before: obj1[key],
        after: obj2[key]
      }
    }
  }

  return differences;
}

function isEqual(value1, value2) {
  return JSON.stringify(value1) === JSON.stringify(value2);
}
439 chars
23 lines

Explanation:

  • diffObjects function receives two objects as parameters.
  • We create an array with all the keys from both objects by using the spread operator (...).
  • We create an empty object to store the differences.
  • For each key in the keys array, we compare the values of the same key in both objects using the isEqual function. If they are not equal, we add the key to the differences object along with the before and after values.
  • Finally, we return the differences object.

Note: The isEqual function compares the values using JSON.stringify, which means that it will not work for values that cannot be parsed into JSON, such as undefined, functions, and symbols.

gistlibby LogSnag