Compare objects in array, merge duplicates with same property value, add property values to the merged object

Tags: , , ,



I have an array of objects and I want to merge objects if they have the same property in object key email. The overlapping properties need to be added to merged object. With new object keys it would be best. This seems to be kind of complicated.

[ { email: 'one@xyz.de',
    SearchQuery: 'Abts, Tomma',
    SearchResult: 1 },
  { email: 'one@xyz.de',
    SearchQuery: 'Ernst, Max',
    SearchResult: 3},
  { email: 'one@xyz.de',
    SearchQuery: 'Sigmund Abeles ',
    SearchResult: 1 },
  { email: 'two@xyz.de',
    SearchQuery: 'Barlach',
    SearchResult: 4 } ]

The result should be something like

[ { email: 'one@xyz.de',
    SearchQuery: 'Abts, Tomma',
    SearchResult: 1 
    SearchQueryTwo: 'Ernst, Max',
    SearchResultTwo: 3
    SearchQueryThree: 'Sigmund, Abeles ',
    SearchResultThree: 1 },
    { email: 'two@xyz.de',
    SearchQuery: 'Barlach',
    SearchResult: 4 } 
]

Answer

It would be possible, but more difficult than it is worth, to have SearchResultOne, SearchResultTwo, SearchResultThree, etc., so it makes more sense to put it into an array:

const inp = [ { email: 'one@xyz.de',
    SearchQuery: 'Abts, Tomma',
    SearchResult: 1 },
  { email: 'one@xyz.de',
    SearchQuery: 'Ernst, Max',
    SearchResult: 3},
  { email: 'one@xyz.de',
    SearchQuery: 'Sigmund Abeles ',
    SearchResult: 1 },
  { email: 'two@xyz.de',
    SearchQuery: 'Barlach',
    SearchResult: 4 } ];
    
const oup = inp.reduce((acc, o) => 
{
  const queryResult = acc.find(qr => qr.email == o.email);
  if(queryResult)
  {
    queryResult.results.push({SearchResult:o.SearchResult, SearchQuery: o.SearchQuery})
  }
  else
  {
    let newQR = {email: o.email, results: [{SearchResult:o.SearchResult, SearchQuery: o.SearchQuery}]};
    acc.push(newQR);
  }
  return acc;
}, []);

console.log(JSON.stringify(oup));


Source: stackoverflow