This post will discuss how to compare two objects in JavaScript. Two objects are considered equal if both objects are of the same type, pass strict equality (===) comparison, and all their properties are equal.

1. Using Lodash/Underscore Library

With lodash or underscore library, you can use the _.isEqual method. It performs a deep comparison between two objects to determine whether they are equivalent. The following code example demonstrates its usage:

Download Code

2. Using JSON.stringify() function

Another solution is to convert both objects into a JSON string and compare their string representation with each other to determine equality. You can use the JSON.stringify() method to convert the JavaScript object to a string.

Download  Run Code

 
This solution does not work when the object contains methods. Also, the solution will fail when the order of the properties is changed.

Download  Run Code

3. Using angular.equals() function

If you’re on angular, you can use the angular.equals() method, which determines if two objects or two objects are equal.

That’s all about comparing two objects in JavaScript.