- Using the “JSON.stringify()” method
- Using the lodash Library’s isEqual() function
Method 1: Using the JSON.stringify() function
It takes an object name as the parameter. Then, the stringify() method converts the entire object into a string data type and then compares the two strings as a string. However, it should be noted that for two different objects to be treated as equal, all the key-value pairs should be equal. Otherwise, the comparison will return false.
On the other hand, another function called isEqualconsidersact that within two different objects, even if the order of the key-value pair is not the same, they are equal.
It returns boolean values, which can either be true or false. For example, if two objects are equal, the output is shown as boolean true, and if the objects are not equal, the output is false.
In this example, we created two objects, f1, and f2, with the same key-value pair. Then we used the JSON.stringify() function and compare both objects. As a result, we are getting true and printing using the console.log() function.
Method 2: Using lodash’s isEqual() function
The isEqual() function has two parameters, obj1, and obj2. So these are two objects that we need to compare.
It returns the Boolean (true or false) value.
We created two objects, f1, and f2, with the same key-value pair in this example.
Here we used the isEqual() function provided by the lodash library to compare f1 and f2 objects. Finally, the result we are printing using the console.log() function.
Using the isEqual() function also, we can perform nested comparisons.
Which method is better to use?
Usually, the key-value pairs are not in the sorted order because they do not need such order or sorting as in arrays, lists, etc., where sorting helps in many operations.
The JSON.stringyfy() will have to transverse the whole object to make the comparison.
On the other hand, the loadash will need less time in most cases because even if there is one mismatching, the function will end the current comparison and return false.
Niva Shah is a Software Engineer with over eight years of experience. She has developed a strong foundation in computer science principles and a passion for problem-solving.