Open In App

Lodash _.mergeWith() Method

Lodash _.mergeWith() method uses a customizer function that is invoked to produce the merged values of the given destination and source properties. When the customizer function returns undefined, the merging is handled by the method instead. It is almost the same as _.merge() method.

Syntax:



_.mergeWith( object, sources, customizer );

Parameters:

Return Value:

This method returns the object.

Example 1: In this example, we are merging two different arrays with the help of the lodash _.mergeWith() method.






// Requiring the lodash library  
const _ = require("lodash");
  
// The destination object
let object = {
    'amit': [{ 'susanta': 20 }, { 'durgam': 40 }]
};
  
// The source object
let other = {
    'amit': [{ 'chinmoy': 30 }, { 'kripamoy': 50 }]
};
  
// Using the _.mergeWith() method 
console.log(_.mergeWith(object, other));

Output:

{ 'amit': [{'chinmoy': 30, 'susanta': 20 }, { 'durgam': 40, 'kripamoy': 50 }] }

Example 2: In this example, we are merging two different arrays which satisfied the given customizer function’s condiiton with the help of the lodash _.mergeWith() method.




// Requiring the lodash library  
const _ = require("lodash");
  
// Defining the customizer function
function customizer(obj, src) {
    if (_.isArray(obj)) {
        return obj.concat(src);
    }
}
  
// The destination object
let object = {
    'amit': [{ 'susanta': 20 }, { 'durgam': 40 }]
};
  
// The source object
let other = {
    'amit': [{ 'chinmoy': 30 }, { 'kripamoy': 50 }]
};
  
// Using the _.mergeWith() method 
console.log(_.mergeWith(object, other, customizer));

Output:

{ 'amit': [{'susanta': 20 }, { 'durgam': 40}, {'chinmoy': 30}, {'kripamoy': 50 } ]} 

Article Tags :