How to do a Deep Comparison Between Two Objects using Lodash?
Last Updated :
23 Jul, 2024
Deep Comparison between two objects is the process of thoroughly checking their properties and nested objects to determine if they are equal.
Below are the possible approaches to do a deep comparison between two objects using Lodash.:
Run the below command to install Loadash JavaScript Library:
npm install loadash
Using _.isEqual() Function
In this approach, we are using Lodash's _.isEqual() function to perform a deep comparison between two objects, obj1, and obj2, checking if their properties and nested arrays are exactly equal. This method returns true if both objects have the same structure and values for all keys and arrays.
Syntax:
_.isEqual(object, other);
Example: The below example uses the _.isEqual() function to do a deep comparison between two objects using Lodash.
JavaScript
const _ = require('lodash');
const obj1 = {
course: 'Data Structures and Algorithms in Python',
duration: '6 Weeks',
instructor: 'GFG',
topics: ['Arrays', 'Linked Lists', 'Stacks', 'Queues']
};
const obj2 = {
course: 'Data Structures and Algorithms in Python',
duration: '6 Weeks',
instructor: 'GFG',
topics: ['Arrays', 'Linked Lists', 'Stacks', 'Queues']
};
const isEqual = _.isEqual(obj1, obj2);
console.log('Objects are equal:', isEqual);
Output:
Objects are equal: true
Using _.isEqualWith() Method with Comparator Function
In this approach, we are using the _.isEqualWith() method from Lodash along with a custom comparator function to perform a deep comparison between two objects. The comparator function checks if the values are arrays and compares them after sorting to handle order differences.
Syntax:
_.isEqualWith(value, other, [customizer]);
Example: The below example uses the _.isEqualWith() Method with Comparator Function to do a deep comparison between two objects using Lodash.
JavaScript
const _ = require('lodash');
const obj1 = {
course: 'Data Structures and Algorithms in Python',
duration: '6 Weeks',
instructor: 'GFG',
topics: ['Arrays', 'Linked Lists', 'Stacks', 'Queues']
};
const obj2 = {
course: 'Data Structures and Algorithms in Python',
duration: '6 Weeks',
instructor: 'GFG',
topics: ['Arrays', 'Linked Lists', 'Stacks', 'Queues']
};
const comparator = (value1, value2) => {
if (_.isArray(value1) && _.isArray(value2)) {
return _.isEqual(_.sortBy(value1), _.sortBy(value2));
}
return undefined;
};
const res = _.isEqualWith(obj1, obj2, comparator);
console.log('Objects are equal:', res);
Output:
Objects are equal: true
Using _.differenceWith() for Array Comparison
In this approach, we use Lodash's _.differenceWith() function to compare arrays of objects. This method checks for differences between two arrays of objects using a custom comparator function.
Syntax:
_.differenceWith(array, [values], [comparator]);
Example:
JavaScript
const _ = require('lodash');
const arr1 = [
{ id: 1, name: 'Nikunj' },
{ id: 2, name: 'Dhruv' }
];
const arr2 = [
{ id: 1, name: 'Nikunj' },
{ id: 2, name: 'Dhruv' }
];
const comparator = (obj1, obj2) => _.isEqual(obj1, obj2);
const differences = _.differenceWith(arr1, arr2, comparator);
console.log('Differences:', differences); // Output: []
const arr3 = [
{ id: 1, name: 'Nikunj' },
{ id: 3, name: 'Yash' }
];
const differences2 = _.differenceWith(arr1, arr3, comparator);
console.log('Differences:', differences2); // Output: [{ id: 2, name: 'Dhruv' }]
Output:
[{ id: 2, name: 'Dhruv' }]
In this approach, we use Lodash’s _.transform() function to perform a custom deep comparison between two objects. This method allows us to compare each property of the objects recursively and handle differences according to custom logic.
Syntax:
_.transform(object, [iteratee], [accumulator]);
Example: The below example uses the _.transform() function to do a deep comparison between two objects using Lodash.
JavaScript
const _ = require('lodash');
const obj1 = {
course: 'Data Structures and Algorithms in Python',
duration: '6 Weeks',
instructor: 'GFG',
topics: ['Arrays', 'Linked Lists', 'Stacks', 'Queues'],
person: 'Nikunj'
};
const obj2 = {
course: 'Data Structures and Algorithms in Python',
duration: '6 Weeks',
instructor: 'GFG',
topics: ['Arrays', 'Linked Lists', 'Stacks', 'Queues'],
person: 'Dhruv'
};
const customDeepComparison = (obj1, obj2) => {
return _.transform(obj1, (result, value, key) => {
if (!_.isEqual(value, obj2[key])) {
result[key] = value;
}
}, {});
};
const differences = customDeepComparison(obj1, obj2);
const isEqual = _.isEmpty(differences);
console.log('Objects are equal:', isEqual);
console.log('Differences:', differences);
Output:
Objects are equal: false
Differences: { person: 'Nikunj' }
Similar Reads
How to Compare Two Objects using Lodash?
To compare two objects using lodash, we employ Lodash functions such as _.isEqual(), _.isMatch(), and _.isEqualWith(). These methods enable us to do a comparison between two objects and determine if they are equivalent or not. Below are the approaches to do a comparison between two objects using Lod
4 min read
How to Find Property by Name in a Deep Object Using Lodash?
When working with deeply nested objects in JavaScript, finding a specific property can be challenging. Using Lodash, a powerful utility library, simplifies this task with its robust set of functions. This guide explores how to effectively search for a property by name within a deeply nested object u
2 min read
How to Filter Key of an Object using Lodash?
Filtering keys of an object involves selecting specific keys and creating a new object that contains only those keys. Using Lodash, this process allows you to include or exclude properties based on specific criteria, simplifying object manipulation. Below are the approaches to filter keys of an obje
2 min read
How to Convert Object Array to Hash Map using Lodash ?
Converting an Object Array to a Hash Map consists of manipulating the array elements to create a key-value mapping. Below are the different approaches to Converting an object array to a hash map using Lodash: Table of Content Using keyBy() functionUsing reduce functionRun the below command before ru
2 min read
How to use Lodash to Find & Return an Object from Array ?
JavaScript's built-in array methods offer basic functionality whereas Lodash, a popular utility library, empowers developers with robust tools for complex array operations. Below are the methods to find and return an object from array using Lodash: Table of Content Using _.find()Using _.findIndex()
3 min read
How to use Lodash to find & Return an Object from Array ?
In JavaScript, the Lodash Module has different methods of doing and get objects from the array. we will explore three different methods with practical implementation of each approach in terms of examples and output to to find and return an object from Array. These are the following methods: Table of
3 min read
How to Find & Update Values in an Array of Objects using Lodash ?
To find and update values in an array of objects using Lodash, we employ utility functions like find or findIndex to iterate over the elements. These functions facilitate targeted updates based on specific conditions, enhancing data manipulation capabilities. Table of Content Using find and assign F
4 min read
How To Get Duplicate Object Fields From Collection Using Lodash?
Finding duplicate object fields in a collection is a common problem when working with large datasets. Lodash provides several utilities that can help identify these duplicates easily by comparing properties within arrays of objects. In this article, weâll explore different approaches to g duplicate
3 min read
How to Replace Objects in Array using Lodash?
Replacing objects in an array using Lodash typically involves identifying the specific object(s) you want to replace and then performing the replacement operation. Lodash provides a range of methods to facilitate such operations, although the actual replacement might involve combining Lodash functio
3 min read
How to Convert Object to Array in Lodash ?
Converting an Object to an Array consists of changing the data structure from key-value pairs to an array format. Below are the different approaches to converting objects to arrays in Lodash: Table of Content Using toArray function Using values functionRun the below command before running the below
2 min read