To check if two objects are equal, you can first make both the objects into a JSON string using the JSON.stringify()
method and then check to see if the string representation of both the objects is equal in JavaScript.
NOTE: For this method to work both the object's keys should be of the same order.
For example, let's say we have 2 objects with a property called name
and value of John Doe
like this,
// 2 objects with same the property and values
const obj1 = { name: "John Doe" };
const obj2 = { name: "John Doe" };
// Check if 2 objects are equal using
// the JSON.stringify() method
JSON.stringify(obj1) === JSON.stringify(obj2); // true
-
The above expression will return boolean
true
since the string representation of objects is equal and we can infer that objects are also equal. -
Using
JSON.stringify()
method is a fast approach.
See the above code live in JSBin.