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.
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.
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
CONTRIBUTOR
View all Courses