i have this array of object as follows
let data = [
{ "id": "12", "values": [ "_status.com", "_verify.com" ] },
{ "id": "12", "values": [ "_result.com"] },
{ "id": "15", "values": [ "_integrate.com"] }
]
If you notice, array of object has 2 objects with the same id 12
and it has 3 variables in values
combined together. Similarly id 15
has only one values variable.
How do i group them together and accumulate the values property in one array. I want to achieve below result.
let result = [
{ "id": "12", "values": [ "_status.com", "_verify.com", "_result.com" ] },
{ "id": "15", "values": [ "_integrate.com"] }
]
can someone let me know how to achieve this. i did search online regarding iteration of array of objects but this is a very unique and different example and i could not find anything close to solving it.
2
Answers
Using
reduce
by iterating through thedata
array.For each object in the array, check if an entry for the
id
already exists in the accumulator object (acc
):Finally use
Object.values()
to extract the accumulated values as an array and assign it to the result variableYou could also
Object.groupBy
theid
‘s and thenmap()
the objects to combine thevalues