0

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 } 
]
2
  • 1
    where are you stuck, can you please post what have you tried? Commented Sep 25, 2020 at 10:45
  • 3
    maybe instead of having SearchQuery, SearchQueryTwo, etc, make an array out of it? That way, every object will always have the same number of properties Commented Sep 25, 2020 at 10:46

1 Answer 1

2

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));

Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot! For everybody who is interested in flattening the results array afterwards check: stackoverflow.com/questions/50262000/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.