How to do a deep comparison between two objects using Lodash
Overview
In Lodash, we can deeply compare two objects using the _.isEqual() method. This method will compare both values to determine if they are equivalent.
Syntax
_.isEqual(value1, value);
Syntax of _.isEqual()
Parameters
This method accepts the following parameters:
value1: This is the value to be compared.value2: This is the other value to be compared.
Return value
This method returns true if both values are equivalent, and vice-versa.
Example
Let’s look at an example of a deep comparison between two objects using the _.isEqual() method in the code snippet below.
Explanation
In the HTML tab, we see the following:
- Line 5: We import the
lodashscript.
In the JavaScript tab, we see the following:
- Line 2–14: We create three objects, namely
obj1,obj2, andobj3respectively, and initialize them.
- Line 17: We do a deep comparison between
obj1andobj2and print the result on the console.
- Line 18: We do a deep comparison between
obj1andobj3and print the result on the console.