[英]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: '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 }
]
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:拥有
SearchResultOne
、 SearchResultTwo
、 SearchResultThree
等是可能的,但比它的价值更难,因此将其放入数组更有意义:
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.