- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Merge and group object properties in JavaScript
Suppose, we have an array of objects like this −
const arr = [ {name: 'lorem', age: 20, color:'red'}, {name: 'lorem', weight: 1, height:5} , {name: 'hello', ipsum : 'dolor'} ];
We are required to write a JavaScript function that takes in one such array of objects. The function should group all the properties of those objects that have the value for "name" property in common.
For example −
For the above array, the output should look like −
const output = [ {name: 'lorem', age : 20, color: 'red', weight : 1, height : 5}, {name: 'hello', ipsum : 'dolor'} ];
Example
The code for this will be −
const arr = [ {name: 'lorem', age: 20, color:'red'}, {name: 'lorem', weight: 1, height:5} , {name: 'hello', ipsum : 'dolor'} ]; const mergeList = (arr = []) => { const temp = {}; arr.forEach(elem => { let name = elem.name; delete elem.name; temp[name] = { ...temp[name], ...elem }; }); const res = []; Object.keys(temp).forEach(key => { let object = temp[key]; object.name = key; res.push(object); }); return res; }; console.log(mergeList(arr));
Output
And the output in the console will be −
[ { age: 20, color: 'red', weight: 1, height: 5, name: 'lorem' }, { ipsum: 'dolor', name: 'hello' } ]
- Related Articles
- JavaScript group a JSON object by two properties and count
- Merge object properties through unique field then print data - JavaScript
- JavaScript Object Properties
- JSON group object in JavaScript
- Group values in array by two properties JavaScript
- How to merge properties of two JavaScript Objects dynamically?
- Merge object & sum a single property in JavaScript
- How to duplicate Javascript object properties in another object?
- Merge duplicate and increase count for each object in array in JavaScript
- How can I merge properties of two JavaScript objects dynamically?
- How to create object properties in JavaScript?
- Extract properties from an object in JavaScript
- How to delete object properties in JavaScript?
- Group by JavaScript Array Object
- How to add properties and methods to an object in JavaScript?

Advertisements