How do I compare two objects for equality in JavaScript?
Rashid D
rashid d profile pic

Comparing two objects for equality in JavaScript requires checking if their properties and values are the same. Here are some approaches you can use: 1. Shallow Equality: - Shallow equality compares the properties and values of the objects at the top level, but it does not perform a deep comparison of nested objects or arrays. - One way to check for shallow equality is by using theisEqual() method from external libraries like Lodash or Underscore.js. - Here's an example using Lodash:

1
2
3
4
5
6
7

   const _ = require('lodash');

   function shallowEqual(obj1, obj2) {
     return _.isEqual(obj1, obj2);
   }
   

2. Deep Equality: - Deep equality compares the properties and values of the objects at all levels, including nested objects and arrays. - One approach to perform a deep equality check is by using recursion to iterate through the properties and values of both objects. - Here's an example of a deep equality comparison function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

   function deepEqual(obj1, obj2) {
     if (obj1 === obj2) {
       return true;
     }

     if (
       typeof obj1 !== 'object' ||
       obj1 === null ||
       typeof obj2 !== 'object' ||
       obj2 === null
     ) {
       return false;
     }

     const keys1 = Object.keys(obj1);
     const keys2 = Object.keys(obj2);

     if (keys1.length !== keys2.length) {
       return false;
     }

     for (let key of keys1) {
       if (!keys2.includes(key) || !deepEqual(obj1[key], obj2[key])) {
         return false;
       }
     }

     return true;
   }
   

In this example, thedeepEqual function checks if the objects are strictly equal (obj1 === obj2) and if they are of type "object." Then, it compares the lengths of the keys of both objects and recursively checks if each key-value pair is equal. 3. JSON Comparison: - Another approach is to convert the objects to JSON strings and compare the resulting strings. This approach works well for simple objects but may not be suitable for objects with complex types or functions. - Here's an example:

1
2
3
4
5
6
7

   function jsonEqual(obj1, obj2) {
     const json1 = JSON.stringify(obj1);
     const json2 = JSON.stringify(obj2);
     return json1 === json2;
   }
   

This approach converts both objects to JSON strings usingJSON.stringify() and then compares the resulting strings for equality. Choose the appropriate approach based on your specific needs and the complexity of the objects you want to compare. Keep in mind that deep equality checks can be computationally expensive, especially for large objects with many nested levels.