How to compare two objects in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

Objects are not like arrays or strings. So simply comparing by using "===" or "==" is not possible. Here to compare we have to first stringify the object and then using equality operators it is possible to compare the objects. 

In the following example, objects were stringified() at first and then compared with each other.

Example

Live Demo

<html>
<body>
   <script>
      const obj1 = {Name: "Rahim", City: 'Hyderabad',Country: "India" };
      const obj2 = {Name: "Rahim", City: 'Hyderabad',Country: "India" };
      document.write(JSON.stringify(obj1) === JSON.stringify(obj2));
   </script>
</body>
</html>

Output

true

If we look at the following example, even though the same properties were repeated, their order is different. In this case, object comparison would result in false as shown in the output.

Example

Live Demo

<html>
<body>
   <script>
      const obj1 = {Name: "Rahim", City: 'Hyderabad', Country: "India" };
      const obj2 = {Name: "Rahim", Country: "India", City: 'Hyderabad', };
      document.write(JSON.stringify(obj1) === JSON.stringify(obj2));
   </script>
</body>
</html>

Output

false

So to overcome this drawback, a javascript library named 'lodash' is introduced. It checks whether the key/value pairs are equal or not but not their order. 

Example

In the following example "_isEqual()" property of lodash is used to compare javascript objects.    

Live Demo

<html>
<head>
   <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>
</head>
<body>
   <script>
      const obj1 = {Name: "Rahim", City: 'Hyderabad', Country: "India" };
      const obj2 = {Name: "Rahim", Country: "India", City: 'Hyderabad', };
      document.write(JSON.stringify(obj1) === JSON.stringify(obj2));
      document.write("</br>");
      document.write(_.isEqual(obj1, obj2));
   </script>
</body>
</html>

Output

false
true
raja
Published on 05-Jul-2019 18:19:33
Advertisements