Open In App

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 Lodash:

Run the below command to install Lodash JavaScript Library:

npm install lodash

Using Lodash _.isEqual() Method

In this approach, we use the _.isEqual() from Lodash to do a comparison between two values to determine if they are equivalent. This method supports comparing arrays, array buffers, boolean, date objects, maps, numbers, objects, regex, sets, strings, symbols, and typed arrays. 

Syntax:

 _.isEqual( value1, value2);

Example: The below example shows how to do a comparison between 2 objects with lodash using _the .isEqual() Method.

// Defining Lodash variable 
const _ = require('lodash');

// First object
const obj1 = { a: 1, b: { c: 2, d: [3, 4] } };

// Second object
const obj2 = { a: 1, b: { c: 2, d: [3, 4] } };

// Checking for Equal Value 
const isEqual = _.isEqual(obj1, obj2);
console.log(isEqual);

Output:

true

Using Lodash _.isMatch() Method

In this approach, we are using the Lodash _.isMatch() method to perform a partial comparison between other object and sources to determine if the object contains equivalent property values.

Syntax:

_.isMatch(object, source);

Example: The below example shows how to do a comparison between 2 objects with lodash using the _.isMatch() method.

// Defining Lodash variable 
const _ = require('lodash');

// First object
const obj = { a: 1, b: { c: 2, d: [3, 4] } };

// Second object
const source = { b: { c: 2 } };

// Doing a deep comparison
const isMatch = _.isMatch(obj, source);
console.log(isMatch);

Output:

true

Using _.isEqualWith() Method

In this approach, we are using the _.isEqualWith() method to do a deep comparison between two values to determine if they are equivalent. Also, it accepts a customizer which is called to compare values. Moreover, if the customizer used here returns undefined then the comparisons are dealt with by the method instead. 

Syntax:

_.isEqualWith(value, other, [customizer]);

Example: The below example shows how to do a deep comparison between 2 objects with lodash using the isEqualWith() method.

// Import the lodash library
const _ = require('lodash');

// Define two objects to be compared
const obj1 = { a: 1, b: { c: 2, d: [3, 4] } };
const obj2 = { a: 1, b: { c: 2, d: [3, 4] } };
const customizer = (value1, value2) => {
    
    // Check if both values are arrays
    if (_.isArray(value1) && _.isArray(value2)) {
        
        // If both values are arrays, compare them after sorting
        return _.isEqual(_.sortBy(value1), _.sortBy(value2));
    }
};
const isEqualWith = _.isEqualWith(obj1, obj2, customizer);
console.log(isEqualWith);

Output:

true
Article Tags :