Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (161).NET Core  (29).NET MAUI  (63)Angular  (74)ASP.NET  (50)ASP.NET Core  (79)ASP.NET MVC  (88)Azure  (36)Blazor  (152)DocIO  (23)Essential JS 2  (85)Essential Studio  (172)File Formats  (28)Flutter  (123)JavaScript  (186)Microsoft  (113)PDF  (67)React  (62)Succinctly series  (128)Syncfusion  (609)TypeScript  (31)Uno Platform  (3)UWP  (4)Vue  (39)Webinar  (35)Windows Forms  (59)WinUI  (52)WPF  (138)Xamarin  (155)XlsIO  (25)Other CategoriesBarcode  (5)BI  (29)Bold BI  (5)Build conference  (6)Business intelligence  (54)Button  (4)C#  (119)Chart  (57)Cloud  (12)Company  (445)Dashboard  (8)Data Science  (3)Data Validation  (6)DataGrid  (55)Development  (396)Doc  (7)DockingManager  (1)eBook  (96)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (23)Extensions  (18)File Manager  (4)Gantt  (11)Gauge  (11)Git  (4)Grid  (28)HTML  (10)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (311)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (30)Performance  (9)PHP  (1)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (7)Road Map  (10)Scheduler  (36)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (22)Solution Services  (3)Spreadsheet  (11)SQL  (8)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (11)Tips and Tricks  (92)UI  (224)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (23)Visual Studio Code  (17)Web  (373)What's new  (213)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Share on twitter
Share on facebook
Share on linkedin
5 Different Ways to Deep Compare JavaScript Objects

5 Different Ways to Deep Compare JavaScript Objects

JavaScript has 7 primitive data types. We can compare the values of any of these types using an equality operator. However, comparing non-primitive types such as objects is tricky since the usual equality operators do not compare object values as one might expect.

In this article, we will discuss five different ways to determine the equality of JavaScript objects.

Two types of equalities in JavaScript

When discussing object comparisons in JavaScript, there are two types of equalities one must be aware of:

  • Referential equality: Determines whether the two provided operands refer to the same reference/object instance.
  • Deep equality: Determines whether objects are equal by comparing each property in the operands.

Referential equality can be determined with equality operators such as strict equality (===) or coercive equality (==) and also by using Object.is() functions, but determining deep equality is tricky as the objects can be nested. However, the following five ways of performing object comparisons make developers’ work easier when a deep equality comparison is required.

Explore the best and most comprehensive JavaScript UI controls library in the market.

Manual comparison

The apparent first thought on anyone’s mind for this problem would be to take each property and compare it against the other operand’s properties and values. But, as mentioned before, these objects can have nested properties. Hence, we have to use a recursive method to compare these nested objects.

A recursive method implementation like the following should be able to tell us whether two given objects are deep equal.

const person1 = {
    "firstName": "John",
    "lastName": "Doe",
    "age": 35 
};

const person2 = {
    "firstName": "John",
    "lastName": "Doe",
    "age": 35,
};
 
const isDeepEqual = (object1, object2) => {

  const objKeys1 = Object.keys(object1);
  const objKeys2 = Object.keys(object2);

  if (objKeys1.length !== objKeys2.length) return false;

  for (var key of objKeys1) {
    const value1 = object1[key];
    const value2 = object2[key];

    const isObjects = isObject(value1) && isObject(value2);

    if ((isObjects && !isDeepEqual(value1, value2)) ||
      (!isObjects && value1 !== value2)
    ) {
      return false;
    }
  }
  return true;
};

const isObject = (object) => {
  return object != null && typeof object === "object";
};

console.log(isDeepEqual(person1, person2)); //true

JSON.stringify() method

This method is more of a trick that we can use to determine whether two objects are deep equal or not. Even though JavaScript does not have an out-of-the-box solution to compare two objects, it has no problem comparing two strings. Therefore, in this method, we convert our two objects into strings using the JSON.stringify() method and compare the two values to determine whether the objects are deep equal. Even if the objects have nested properties, this method can handle those as well. It is important to note that this method uses strict equality (===) on attributes; therefore, having ages as 35 and “35” will not be equal.

const person1 = {
    "firstName": "John",
    "lastName": "Doe",
    "age": 35 
}

const person2 = {
    "firstName": "John",
    "lastName": "Doe",
    "age": 35 
}

JSON.stringify(person1) === JSON.stringify(person2); // true

This method has one downside, however. Take the above example and alter the order of the attributes in the object person2.

const person2= {
    "age": 35,
    "firstName": "John",
    "lastName": "Doe"
}

Since the object attributes and their values have not changed, we would expect to return true when the objects are compared. Since the generated strings are different this time due to the difference in the order, the comparison will return false.

Therefore, it is important to note that having different orders of attributes can give incorrect results when using this method.

Everything a developer needs to know to use JavaScript control in the web app is completely documented.

Comparisons using Lodash library

The famous Lodash library also provides a method to determine deep equality between two objects. Using the isEqual() method from this library, we can perform a deep comparison between the given operands. It will return a Boolean value indicating whether the operands are equal based on JavaScript strict equality (===) on all attributes of the two given objects.

const _ = require('lodash');

const person1 = {
    "firstName": "John",
    "lastName": "Doe",
    "age": 35 
}

const person2 = {
    "firstName": "John",
    "lastName": "Doe",
    "age": 35 
}

_.isEqual(person1, person2); // true

According to the Lodash documentation, this method supports arrays, array buffers, date objects, etc. As a bonus, we can download this method as a separate npm module as well.

Comparisons using the deep-equal library

The deep-equal library is another vastly popular NPM module with over 11 million weekly downloads. This library provides the functionality to determine deep equality between two objects.

The deepEqual() method from the library takes three parameters. The first two are the operands to be compared, and the third parameter is an optional options parameter. With the option, we can specify whether to use strict equality (===) or coercive equality (==) to compare the leaf nodes. The default option is to use coercive equality to compare leaf nodes.

const deepEqual = require('deep-equal');

const person1 = {
    "firstName": "John",
    "lastName": "Doe",
    "age": 35 
}

const person2 = {
    "firstName": "John",
    "lastName": "Doe",
    "age": "35" 
}
deepEqual(person1, person2); // true

Note that the age value is a number in the person1 object and a string in the person2 object. Since the strict option is false by default, the deep-equal library uses coercive equality on the leaf nodes, so this function returns true. If the strict parameter of the function is set to true, this method would return false.

const person2 = {
    "firstName": "John",
    "lastName": "Doe",
    "age": "35" 
}

deepEqual(person1, person2, {strict: true}); // false

//When person2 values are updated with the same data types as person1.
const person2 = {
    "firstName": "John",
    "lastName": "Doe",
    "age": 35 
}

deepEqual(person1, person2, {strict: true}); // true

Syncfusion JavaScript controls allow you to build powerful line-of-business applications.

Framework-specific methods

Some JavaScript frameworks, such as Angular and Nodejs, provide built-in functionality to determine deep equality in their frameworks.

  • Node.js: assert.deepStrictEqual(actual, expected, message)
    The deepStrictEqual() method provided by the assert module is a built-in method in Node.js that takes three parameters: the two operands and a message as an optional parameter that will be used when an error is thrown if the two operands are not equal. This method will check for strict equality on leaf nodes. It will return undefined if the operands are equal and will throw an error if they are not deep and strictly equal.

    const assert = require('assert');
    
    const person1 = {
        "firstName": "John",
        "lastName": "Doe",
        "age": 35 
    }
    
    const person2 = {
        "firstName": "John",
        "lastName": "Doe",
        "age": 35 
    }
    
    console.log(assert.deepStrictEqual(person1, person2)); //true
  • Angular: angular.equals(obj1, obj2)
    The Angular library also provides a method that helps us to determine deep equality between two objects. This method is provided under the ng module. It takes two parameters, the operands, to be compared for equality and returns a Boolean value indicating whether the operands are equal based on JavaScript strict equality (===).

    var person1 = {
      firstName: "John",
      lastName: "Doe",
      age: 35,
    };
     
    var person2 = {
      firstName: "John",
      lastName: "Doe",
      age: 35,
    };
     
    console.log(angular.equals(person1, person2)); //true

Conclusion

JavaScript deep object comparison can be tricky, so careful handling is required. As discussed above, there are many methods, including third-party libraries, that help us to determine deep equality between objects. To select the suitable method for a use case, one must consider each method’s requirements and options.

I hope this article will help you to make the right decision. Thank you for reading.

Syncfusion Essential JS 2 is the only suite you will ever need to build an app. It contains over 65 high-performance, lightweight, modular, and responsive UI components in a single package. Download a free trial to evaluate the controls today.

If you have any questions or comments, you can contact us through our support forumssupport portal, or feedback portal. We are always happy to assist you!

Related blogs

Tags:

Share this post:

Share on twitter
Share on facebook
Share on linkedin
Popular Now

Be the first to get updates

Subscribe RSS feed
Scroll To Top