I have an array of objects, where each object has a property whose value is another array, like this
[
{
location: 'somewhere',
location_id: 1,
parts: [
{
part_id: 1,
description: 'foo',
qty: 1,
}
]
}
]
I need to map these arrays into a single array like this
[
{
part_id: 1,
description: 'foo',
qty: 1
},
{
part_id: 2,
description: 'bar',
qty: 1
}
]
I tried using reduce like
newArr: arr.reduce((a,b) => a.parts.concat(b.parts)) but get the error 'Cannot read property concat of undefined.' I also tried providing the initialValue argument of reduce as an empty array but same error.
As a bonus, I will eventually need the final array to not contain duplicates of parts: I.e. if a part is in two locations, it would just combine the quantity.
Open to solutions using es6 but needs to not modify original array
reducecallback is the accumulator array, so it won't have apartsproperty.[].concat(...arr.map(item => item.parts))Doesn't create that many intermediate Arrays as the approach withreducepart_id: 2, description: 'bar'when there's nothing in the input that resembles it?