Equality for two JavaScript objects
Objects are the reference type in JavaScript and are also named value pairs, where the value may determine a property or behaviour. They are used extensively because nowadays the web development has changed vastly. This article describes how to compare two JavaScript objects in the following formats:
- Comparing JavaScript Objects based on reference
- Comparing Two JavaScript Objects based on the data it contains
Method 1: Comparing two objects based on reference: The strict equals (===) operator compares memory locations in case of comparing objects.
Example:
JavaScript
<script> // Creating two Objects with same data object1 = { name: "GeeksForGeeks" , founder: "SandeepJain" }; object2 = { name: "GeeksForGeeks" , founder: "SandeepJain" }; // In this case, obj1 and obj2 // have different memory locations // therefore === returns false check = (object1 === object2); document.write( "Does Object1 " + "equals Object2 ? : " + check); // Going to the next line document.write( "< p > </ >" ); // Pointing to same reference now object1 = object2; check = (object1 === object2); document.write( "Does Object1 equals" + " Object2 ? : " + check); </script> |
Output:
Method 2: Comparing Two JavaScript Objects based on the data:
Example 1:
JavaScript
<script> <script> // Creating two objects with // a method inside it object1 = { name: "GeeksForGeeks" , author: "Jagannath" , greet: () => { document.write( "Hello Geeks" ); } }; object2 = { name: "GeeksForGeeks" , author: "Jagannath" , greet: () => { document.write( "Hello Geeks" ); } }; string1 = JSON.stringify(object1); string2 = JSON.stringify(object2); check = (string1 === string2); document.write( "Is the data same in" + " Object1 and Object2 ?: " + check); </script> |
Output:
Example 2:Drawback of using JSON.stringify() method. If the order of data inside an object changes, then the above method does not work properly. This is the drawback of using JSON.stringify() method as demonstrated below.
JavaScript
<script> // Creating two objects with // a method inside it object1 = { name: "GeeksForGeeks" , author: "Jagannath" , greet: () => { document.write( "Hello Geeks" ); } }; // Changing the order of the // values defined in the // second object object2 = { author: "Jagannath" , name: "GeeksForGeeks" , greet: () => { document.write( "Hello Geeks" ); } }; string1 = JSON.stringify(object1); string2 = JSON.stringify(object2); check = (string1 === string2); document.write( "Is the data same in " + "Object1 and Object2 ?: " + check); </script> |
Output:
Please Login to comment...