How to Compare Objects for Equality in JavaScript?

When working with JavaScript it is common to compare objects for equality. we will explore various approaches to compare objects for equality in JavaScript.

These are the following approaches:

Table of Content

  • Using JSON.stringify
  • Using Lodash’s isEqual() Method

Using JSON.stringify

In this approach, we convert the objects to JSON strings using JSON.stringify and compare the resultant strings for equality.

Example: The below example uses the JSON.stringify method to Compare Objects for Equality.

JavaScript
const isEqual = (obj1, obj2) => JSON.stringify(obj1) === JSON.stringify(obj2);
const obj1 = { org: 'BeginnerForGeek',
               founder: "Sandeep Jain" };
const obj2 = { org: 'BeginnerForGeek',
               founder: "Sandeep Jain" };

console.log(isEqual(obj1, obj2));

Output
true

Using Lodash’s isEqual() Method

In this approach, we are using Lodash’s isEqual() Method. The isEqual() method is used to deeply compare two values to determine if they are equivalent.

Example: Below example uses Lodash’s isEqual() method to Compare Objects for Equality.

JavaScript
const isEqual = require('lodash/isEqual');

const obj1 = { org: 'BeginnerForGeek',
               founder: "Sandeep Jain" };
const obj2 = { org: 'BeginnerForGeek',
               founder: "Sandeep Mishra" };

console.log(isEqual(obj1, obj2));

Output:

false

Contact Us