Merge and group object properties in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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' }
]
raja
Published on 23-Nov-2020 07:30:06
Advertisements