Compare two objects in JavaScript
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:
|
1 2 3 4 5 6 7 |
var _ = require('underscore'); // lodash let obj1 = { name: 'Max', age: 25 }; let obj2 = { name: 'Max', age: 25 }; let isEqual = _.isEqual(obj1, obj2); console.log(isEqual); |
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.
|
1 2 3 4 5 |
let obj1 = { name: 'Max', age: 25 }; let obj2 = { name: 'Max', age: 25 }; let isEqual = JSON.stringify(obj1) === JSON.stringify(obj2); console.log(isEqual); |
This solution does not work when the object contains methods. Also, the solution will fail when the order of the properties is changed.
|
1 2 3 4 5 |
let obj1 = { age: 25, name: 'Max' }; let obj2 = { name: 'Max', age: 25 }; let isEqual = JSON.stringify(obj1) === JSON.stringify(obj2); console.log(isEqual); |
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.
|
1 2 3 4 5 |
let obj1 = { name: 'Max', age: 25 }; let obj2 = { name: 'Max', age: 25 }; let isEqual = angular.equals(obj1, obj2); console.log(isEqual); |
That’s all about comparing two objects in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)