JavaScript objects allow you to easily store diverse types of data in a single variable, in a compact manner. Often you may need to compare objects in JavaScript. Typically, developers are tempted to compare two objects using equality operator ‘==’ or ‘===’ but neither of these operators give the right result, for reasons mentioned below. In this article, we will learn how to compare objects in JavaScript.
How to Compare Objects in JavaScript
Let us say you have the following 3 objects x, y, z.
var x = {}; var y = {}; var z = x;
Let us say you compare them using equality operator as shown below.
x === y; // => false x === z; // => true
In such cases, it is better to compare the individual items of both objects, one by one, instead of comparing the entire object at one go, and returning true if all elements of one object are present in the other and vice versa.
It can be tedious to do this using plain JavaScript so it is advisable to do this using third party JavaScript libraries such as Underscore.js, Lodash (fork of Underscore), AngularJS, etc.
Let us say you have two JS objects as shown below.
var obj1 = [{"New": "York"}]; var obj2 = [{"York": "York"}]; var obj3 = [{"York": "Jersey"}];
Here are simple code snippets to test the equality of two objects using different libraries.
Using Lodash
Lodash provides a isEqual() function for this purpose. Include the following line in your web page to import Lodash library.
<script src='https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js'></script>
Here is the code to compare two objects.
_.isEqual(obj1, obj2); //returns true _.isEqual(obj1, obj3); //returns false
If you don’t want to import the entire Lodash library into your web page, you can import just the equality function using this link.
Using AngularJS
Include the following line in your web page to import AngularJS library.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
You can compare the equality of objects using the equals() function.
function compare_obj(obj1, obj2){ if(angular.equals(obj1, obj2)) { document.write('true'); }else{ document.write('false'); } } console.log(compare_obj(obj1, obj2)); //returns true console.log(compare_obj(obj1, obj3)); //returns false
In this article, we have learnt how to easily compare JS objects.
Also read:
How to Group By Array of Objects By Key
How to Find Element Using XPath in JavaScript
How to Remove Submodule in Git
How to Merge Two Git Repositories
How to Setup Username & Password for Different Repos