Search code examples
javascriptnode.jsarraysjavascript-objects

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


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: '[email protected]',
    SearchQuery: 'Abts, Tomma',
    SearchResult: 1 },
  { email: '[email protected]',
    SearchQuery: 'Ernst, Max',
    SearchResult: 3},
  { email: '[email protected]',
    SearchQuery: 'Sigmund Abeles ',
    SearchResult: 1 },
  { email: '[email protected]',
    SearchQuery: 'Barlach',
    SearchResult: 4 } ]

The result should be something like

[ { email: '[email protected]',
    SearchQuery: 'Abts, Tomma',
    SearchResult: 1 
    SearchQueryTwo: 'Ernst, Max',
    SearchResultTwo: 3
    SearchQueryThree: 'Sigmund, Abeles ',
    SearchResultThree: 1 },
    { email: '[email protected]',
    SearchQuery: 'Barlach',
    SearchResult: 4 } 
]

Solution

  • 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: '[email protected]',
        SearchQuery: 'Abts, Tomma',
        SearchResult: 1 },
      { email: '[email protected]',
        SearchQuery: 'Ernst, Max',
        SearchResult: 3},
      { email: '[email protected]',
        SearchQuery: 'Sigmund Abeles ',
        SearchResult: 1 },
      { email: '[email protected]',
        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));