Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript

How to compare two objects in JavaScript

Nouman Abbasi

Usually, when you compare data types like int and strings in JavaScript, you use the equality operators (== and ===). However, comparing objects with == and === will not work.

To fix this, one option is to stringify both objects and then use the equality operators.

Using JSON.stringify()

We first convert the objects to their stringified version using JSON.stringify() and then compare them using ===:

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

console.log(JSON.stringify(obj1) === JSON.stringify(obj2)); // true

If the order of the properties is different, the above method will evaluate as false even though the properties are the same:

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

console.log(JSON.stringify(obj1) === JSON.stringify(obj2)); // false

To overcome this issue, we can use a JavaScript library, called lodash, instead.

Using lodash

lodash is a JavaScript library that offers _.isEqual(value1, value2), which performs a deep comparison between two values to check if they are equivalent.

import _ from "lodash";

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

console.log(_.isEqual(obj1, obj2)); // true

RELATED TAGS

javascript

CONTRIBUTOR

Nouman Abbasi
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring