Skip to content
Advertisement

Merge duplicate objects in array of objects

I have below array of objects,

JavaScript

I want to merge the duplicate objects based on attribute ‘label’ so that Final output will look like below,

JavaScript

Can someone help me identify the approach?

Advertisement

Answer

I would probably loop through with filter, keeping track of a map of objects I’d seen before, along these lines (edited to reflect your agreeing that yes, it makes sense to make (entry).data always an array):

JavaScript

In an ES6 environment, I’d use seen = new Map() rather than seen = {}.

Note: Array.isArray was defined by ES5, so some quite older browsers like IE8 won’t have it. It can easily be shimmed/polyfilled, though:

JavaScript

Side note: I’d probably also always make entry.data an array, even if I didn’t see two values for it, because consistent data structures are easier to deal with. I didn’t do that above because your end result showed data being just a string when there was only one matching entry. (We’ve done that above now.)

Live example (ES5 version):

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement