How to Get the Difference Between Two JavaScript Objects

Get the list of the keys that are different between two objects using the Lodash isEqual method.

Often when debugging JavaScript applications, it can be useful to know the differences between objects, for example, to see what has changed in the props supplied to a React component when it re-renders.

A magnifying glass

This function uses the Lodash isEqual method to quickly provide you with a list of the keys that are different between two objects:

const getObjectDiff = (obj1, obj2, compareRef = false) => {
  return Object.keys(obj1).reduce((result, key) => {
    if (!obj2.hasOwnProperty(key)) {
      result.push(key);
    } else if (_.isEqual(obj1[key], obj2[key])) {
      const resultKeyIndex = result.indexOf(key);

      if (compareRef && obj1[key] !== obj2[key]) {
        result[resultKeyIndex] = `${key} (ref)`;
      } else {
        result.splice(resultKeyIndex, 1);
      }
    }
    return result;
  }, Object.keys(obj2));
}

Calling this with two objects will return an array of the names of keys on the objects whose values are not equal, and also includes the names of keys that do not exist on both objects. Once you have this top-level information you can then dig deeper if needed to find out exactly what the differences are.

This function also provides an option to compare the references of object properties, and in this case, if the value of a key is equal for both objects but the reference is different, the key name will be returned with (ref) appended to the end. This is particularly relevant for React where shallow comparisons are used to decide whether to re-render pure components, for example.

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics