How to Merge Array of Objects by Property using Lodash?
Merging an array of objects by property using Lodash is a common operation when you need to consolidate data that share a common identifier. For example, if you have a list of user objects and you want to combine them into a single object based on a unique property, Lodash provides useful functions to simplify this process.
Below are different approaches to merging objects in an array by a specific property using Lodash:
Using _.merge( ) and _.groupBy ( )
In this approach, we first group the objects in the array based on a common property using _.groupBy ( ). Then, we merge the objects within each group using _.merge ( ). This method is useful when we have multiple objects that should be combined into one based on a shared key.
Syntax:
const groupedObjects = _.groupBy(array, 'property');
const mergedObjects = _.mapValues(groupedObjects, group => _.merge({}, ...group));
Example: This code groups an array of student objects by their id
and merges the objects within each group into a single object, consolidating information for each student.
// Import lodash using CommonJS require
const _ = require('lodash');
const students = [
{ id: 1, name: 'Geek', grade: 'A' },
{ id: 2, name: 'Geekina', grade: 'B' },
{ id: 1, sports: 'Soccer' },
{ id: 2, sports: 'Basketball' }
];
// Group students by 'id'
const groupedStudents = _.groupBy(students, 'id');
// Merge objects within each group
const mergedStudents =
_.mapValues(groupedStudents, group =>
_.merge({}, ...group));
console.log(mergedStudents);
Output:

Using _.keyBy ( ) and _.assign ( )
In this approach, we first use _.keyBy ( ) to turn the array of objects into an object, where each key is the value of the specified property. Then, we use _.assign ( ) or _.merge ( ) to combine these objects. This method is efficient and works well when we want to quickly merge objects by a property.
Syntax:
const keyedObjects = _.keyBy(array, 'property');
const mergedObject = _.assign({}, keyedObjects);
Example: This code keys an array of student objects by their id
and merges the keyed objects into a single object, consolidating the information for each student.
// Import lodash using CommonJS require
const _ = require('lodash');
const students = [
{ id: 1, name: 'Geek', grade: 'A' },
{ id: 2, name: 'Geekina', grade: 'B' },
{ id: 1, sports: 'Soccer' },
{ id: 2, sports: 'Basketball' }
];
// Key the students by 'id'
const keyedStudents = _.keyBy(students, 'id');
// Merge the keyed student objects
const mergedStudent = _.assign({}, keyedStudents);
console.log(mergedStudent);
Output:
