cancel
Showing results for 
Search instead for 
Did you mean: 

How to merge all objects in an array

khanh_tran
New Contributor II

I got an array named “group” includes object items as the below picture
Screen Shot 2021-07-26 at 15.22.51
How can I merge all object items to one object? My expected result as the below picture. But, imagine that the number of item is unknown. It can be 3,4,5 , … (n).
Screen Shot 2021-07-26 at 15.24.27

Thank you!

1 ACCEPTED SOLUTION

j_angelevski
Contributor III

That won’t be a problem here, because I’m using destructuring assignment ( the three dots ) before the $group array ...$group, this will always work for every $group array regardless of the array size, you don’t have to get each index from the $group array, just use ...$group, this will destructure the array and will be the same as writing $group[0]... $group[n] multiple times.

View solution in original post

12 REPLIES 12

@dd_snaplogic Can you elaborate and share some examples what you mean by that ?

dd_snaplogic
New Contributor II

@j.angelevski Under the group object if I have same key, for example
image

this example as you can see it has same key, so if i use extend function it will override the value with the same key
image
image

Is it possible to keep all the values and generate the matching keys dynamically in the same object.

example:
image
Here is the example slp file
Example Groupby Merge.slp (6.6 KB)

Hi @dd_snaplogic,

The following function will give you the result you need:

$group.reduce((acc,curr)=> acc.extend(curr.filter((v1,k1)=> k1!='abc').mapKeys((v,k)=> k+curr.num)),{}).extend($groupBy)

Keep in mind that this will work only if you group the data by 1 field. If you need it to be grouped on multiple fields, then the expression will have to be amended.

Hope this helps,
Bojan