3 Ways to Compare 2 Objects in JavaScript

Updated: February 19, 2023 By: Wolf Post a comment

This article walks you through 3 different ways to compare 2 objects in Javascript. Without any further ado, let’s get started.

Warning: Using the === operator (the triple equal sign) to compare 2 Javascript objects is incorrect and leads to wrong results.

Using JSON.stringify

A simple way to compare 2 objects in JavaScript is to use JSON.stringify() to convert the objects into strings and then compare the strings. This can handle objects with any depth of nesting.

Example:

const person1 = {
  name: 'John Doe',
  age: 35,
  address: {
    street: 'Main Street',
    city: 'New York',
    state: 'NY',
  },
};

const person2 = {
  name: 'John Doe',
  age: 35,
  address: {
    street: 'Main Street',
    city: 'New York',
    state: 'NY',
  },
};

if (JSON.stringify(person1) === JSON.stringify(person2)) {
  console.log('They are equal');
} else {
  console.log('They are not equal');
}

Output:

They are equal

This technique has some small limitations. If 2 objects have the same properties but in different orders, it will result that they are not equal (this can be good in many cases). The performance can be slower for large and complex objects because of the conversion to a string (big objects are very rare in general projects). In addition, the comparison does not take into account functions, undefined values, or NaN.

Using a custom function

We can write a custom function to compare 2 objects by iterating over the keys of each object and comparing the values. It can be time-consuming to write and may have bugs or edge cases that need to be considered. However, in return, we have complete control over the comparison process as well as the freedom to handle specific use cases and customized needs.

Example

In this example, we will define a function that has the ability to compare deeply nested objects:

// This function can compare deeply nested objects
function deepEqual(object1, object2) {
  const keys1 = Object.keys(object1);
  const keys2 = Object.keys(object2);

  if (keys1.length !== keys2.length) {
    return false;
  }

  for (let key of keys1) {
    const val1 = object1[key];
    const val2 = object2[key];

    const areObjects = isObject(val1) && isObject(val2);
    if (
      (areObjects && !deepEqual(val1, val2)) ||
      (!areObjects && val1 !== val2)
    ) {
      return false;
    }
  }

  return true;
}

// this minor function is used in the 'deepEqual' function above
function isObject(object) {
  return object != null && typeof object === 'object';
}

// try the 'deepEqual' function
const person1 = {
  name: 'John Doe',
  age: 35,
  address: {
    street: 'Main Street',
    city: 'New York',
    state: 'NY',
    contact: {
      phone: 123456789,
      email: '[email protected]',
    },
  },
};

const person2 = {
  name: 'John Doe',
  age: 35,
  address: {
    street: 'Main Street',
    city: 'New York',
    state: 'NY',
    contact: {
      phone: 123456789,
      email: '[email protected]',
    },
  },
};

console.log(deepEqual(person1, person2));

Output:

true

Using lodash

Lodash is a widely-used Javascript library that provides a comprehensive set of functions for object comparison. It can handle objects with any depth of nesting, can compare objects with circular references, as well as can consider differences in property order and types of values (e.g., undefined, NaN, functions). However, using it will add an additional dependency to your project, and it can be slower for large and complex objects.

You can install lodash like any other npm package:

npm i lodash

Example:

import _ from 'lodash'

const object1 = {
    name: 'Sling Academy',
    age: 5,
    topics: ['JavaScript', 'Python', 'Maths']
}

const object2 = {
    name: 'Sling Academy',
    topics: ['JavaScript', 'Python', 'Maths'],
    age: 5
}

if (_.isEqual(object1, object2)) {
    console.log('The objects are equal');
} else {
    console.log('The objects are not equal');
}

Output:

The objects are equal

In the above example, the objects have the same properties but in a different order.

Conclusion

The choice of which approach to use for comparing objects depends on the specific needs of the project. If simplicity and speed are paramount, then JSON.stringify is a good choice. If performance is a concern, or more advanced object comparison features are needed, then Lodash may be the best option. Finally, writing a custom function can be a good choice when specific use cases or customized needs are required, and the developer has the time and expertise to create an efficient and reliable function.

If you have any comments on this article or see something that needs improvement, please leave a comment. We are happy to hear from you.