How to Update an Array of Objects with Another Array of Objects using Lodash?

Updating an array of objects with another array of objects involves merging or updating objects in the first array with corresponding objects from the second array.

Below are the approaches to update an array of objects with another array of objects in the Lodash library:

Table of Content

  • Using _.merge function from lodash
  • Using _.mergeWith function from lodash

To execute the Lodash program, installation via npm is required. This can be achieved by running the following command:

Syntax:

npm install lodash

Using _.merge function from lodash

In this approach, we use the _.merge function from lodash to merge objects from the second array into the first array based on their index positions. If objects with the same index exist in both arrays, properties from the second object overwrite properties in the first object.

Syntax:

_.merge(array1, array2);

Example: To demonstrate the implementation of a program to update an array of objects with another array of objects using _.merge function from lodash

JavaScript
const _ = require('lodash');
const array1 = 
    [{ id: 1, name: 'HTML' }, { id: 2, name: 'CSS' }];
const array2 = 
    [{ id: 1, age: 30 }, { id: 3, name: 'JavaScript' }];
const updatedArray = _.merge(array1, array2);
console.log(updatedArray);

Output:

[
{ id: 1, name: 'HTML', age: 30 },
{ id: 2, name: 'CSS' },
{ id: 3, name: JavaScript' }
]

Using _.mergeWith function from lodash

In this approach we use the _.mergeWith function from lodash, which allows customizing the merging behavior by providing a customizer function. In this case, we use a customizer function that concatenates arrays instead of replacing them.

Syntax:

_.mergeWith(array1, array2, customizer);

Example: To demonstrate the implementation of a program to update an array of objects with another array of objects using _.mergeWith function from lodash

JavaScript
const _ = require('lodash');

const array1 = 
    [{ id: 1, name: 'HTML', hobbies: ['reading'] }, { id: 2, name: 'CSS' }];
const array2 = 
    [{ id: 1, hobbies: ['swimming'] }, { id: 3, name: 'JavsScript' }];

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

const updatedArray = 
    _.mergeWith(array1, array2, customizer);
console.log(updatedArray);

Output:

[
{ id: 1, name: 'HTML', hobbies: ['reading', 'swimming'] },
{ id: 2, name: 'CSS' },
{ id: 3, name: 'JavaScript' }
]