aweber-banner

How to Compare two Objects in JavaScript

In this, tutorial, we will learn How to Compare two Objects in JavaScript.


Objects are reference types so we can’t just use === or == to compare 2 objects.


Instead of this, we can use JSON.stringify() as below:

const obj1 = { name: 'john' };
const obj2 = { name: 'john' };


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


We can also use the isEqual method of Lodash library as below:

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


Above both methods also works for nested objects as well, but note that in JSON.stringify(), the order matters. So if the key-value pair are ordered differently in the two objects but are the same, it will return false. Whereas it doesn't matter in Lodash isEqual, it will return true as along as the key-value pair exists.



Which one to use?

isEqual is better in performance in comparison to JSON stringify, so better to use isEqual.