Skip to content

JavaScript compare two objects | Code

  • by

Unfortunately, there is no perfect way to compare two objects in JavaScript. Or use _proto_ recursively and access all non-enumerable properties, but this works in Firefox only.

You can use JSON stringify with a strict equality operator to compare objects. Another way is using the Lodash isEqual function.

JavaScript compares two objects

Simple example code compares simple JSON-style objects without methods. Objects are reference types so you can’t just use === or == to compare 2 objects.

<!DOCTYPE html>
<html>
<body>

  <script>
   var user1 = {name : "nerd", org: "dev"};
   var user2 = {name : "nerd", org: "dev"};

   var res =  JSON.stringify(user1) === JSON.stringify(user2) 
   console.log("Object are eaual", res)
 </script>

</body>
</html>

Output:

JavaScript compare two objects

The ORDER of the properties IS IMPORTANT, so this method will return false for the following objects:

 x = {a: 1, b: 2};
 y = {b: 2, a: 1};

Source: stackoverflow.com

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

<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: "ABC", City: 'BLR', Country: "India" };
      const obj2 = {Name: "ABC", Country: "India", City: 'BLR', };
      document.write(JSON.stringify(obj1) === JSON.stringify(obj2));
      document.write("</br>");
      document.write(_.isEqual(obj1, obj2));
   </script>
</body>

If you want to compare the contents of two objects, you would need to implement custom comparison logic. One common approach is to iterate over the properties of both objects and compare them individually. There are also libraries like Lodash that provide utility functions for deep comparison of objects.

Do comment if you have any doubts or suggestions on this Js object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *