How to Compare Objects in JavaScript?

In JavaScript, comparing objects is not as simple as comparing numbers or strings. Objects are compared based on their memory references, so even if two objects have the same properties and values, they are considered distinct if they are stored in different memory locations.

Below are the various approaches to compare objects in JavaScript:

Table of Content

  • Equality (===)
  • JSON.stringify()
  • Lodash Library
  • Object.entries()
  • Object.keys()

Equality (===)

This compares the references of the objects. If the references point to the same object, it returns “true”, otherwise “false”.

Syntax:

object_1 === object_2 

Example: To demonstrate the comparison of the JavaScript Object Reference.

JavaScript
// Example of different reference 
const obj1 = { a: 1, b: 2 };
const obj2 = { a: 1, b: 2 };
console.log(obj1 === obj2);

// Example of same reference 
const obj3 = { a: 1, b: 2 };
const obj4 = obj3;
console.log(obj3 === obj4); 

Output:

false
true

JSON.stringify()

This method converts objects into JSON strings and then compares these strings. This method effective only if the objects have the same properties in the same order.

Syntax:

JSON.stringify(obj1) === JSON.stringify(obj2); 

Example: To demonstrate comparing the JavaScript object using the JSON.stingfy().

JavaScript
const obj1 = { a: 1, b: 2 };
const obj2 = { a: 1, b: 2 };
console.log(JSON.stringify(obj1) === JSON
    .stringify(obj2)); 

Output:

true

Lodash Library

Lodash Library offers a convenient isEqual() method specifically designed for deep object comparison.

Install dependencies:

npm install lodash

Syntax:

const lodash = require('lodash');

lodash.isEqual(obj1, obj2));

Example: To demonstrate comparing the JavaScript object using the Lodash Library.

JavaScript
const lodash = require('lodash');

const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { a: 1, b: { c: 2 } };

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

Output:

true

Object.entries()

You can convert objects into arrays of key-value pairs and then compare them.

Example: To demonstrate comparing the JavaScript object using the Object.entries method.

JavaScript
function compareEntries(obj1, obj2) {
    const entries1 = Object.entries(obj1);
    const entries2 = Object.entries(obj2);
    return JSON
        .stringify(entries1) === JSON
            .stringify(entries2);
}

const obj1 = { a: 1, b: 2 };
const obj2 = { a: 1, b: 2 };
console.log(compareEntries(obj1, obj2)); 


Output:

true

Object.keys()

This method involves comparing the keys of two objects directly.

Example: To demonstrate comparing the JavaScript object using the Object.keys() method in JavaScript.

JavaScript
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 2, a: 1 };

const keys1 = Object
    .keys(obj1)
    .sort();
const keys2 = Object
    .keys(obj2)
    .sort();

console.log(JSON.stringify(keys1) === JSON.stringify(keys2));

Output

true