Equality for two JavaScript objects
Last Updated :
05 Jun, 2020
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>
object1 = {
name: "GeeksForGeeks" ,
founder: "SandeepJain"
};
object2 = {
name: "GeeksForGeeks" ,
founder: "SandeepJain"
};
check = (object1 === object2);
document.write( "Does Object1 "
+ "equals Object2 ? : " + check);
document.write( "< p > </ >" );
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>
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>
object1 = {
name: "GeeksForGeeks" ,
author: "Jagannath" ,
greet: () => {
document.write( "Hello Geeks" );
}
};
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:
Share your thoughts in the comments
Please Login to comment...