how to use the mergewith function from lodash in javascript


To use mergeWith() function from Lodash in JavaScript, you need to first import the Lodash library into your project. You can do this using npm or by including the script in your HTML file.

Here is an example of how to use mergeWith() to merge two objects:

index.tsx
const _ = require('lodash');

const object1 = {
  name: 'Alice',
  age: 25
};

const object2 = {
  age: 30,
  email: 'alice@example.com'
};

const customizer = (objValue, srcValue) => {
  if (_.isArray(objValue)) {
    return objValue.concat(srcValue);
  }
};

const mergedObject = _.mergeWith(object1, object2, customizer);

console.log(mergedObject); 
// Output: { name: 'Alice', age: [ 25, 30 ], email: 'alice@example.com' }
428 chars
23 lines

In the above code, we have two objects object1 and object2 that we want to merge into one. We also have a customizer function that we pass as a third parameter to mergeWith() function. This customizer function tells Lodash how to merge two values when they are of the same type, and in our case we use it to merge arrays.

The output of this code will be a new object that contains all the properties of object1 and object2, with the values for the age property merged into an array.

gistlibby LogSnag