Reputation: 147
const all = [{
'name': 'first',
'attributes': [{
'name': 'attr1'
}]
}, {
'name': 'second',
'attributes': [{
'name': 'attr2'
}]
}]
const res = all.reduce((acc, el) => {
return acc + el.attributes
}, [])
console.log(res)
I need get next
result => [{'name':'attr1'}, {'name':'attr2'}]
What is the best way do it, it can be not only reduce.
Upvotes: 0
Views: 53
Reputation: 25634
There's also flatMap
:
const all = [{ name: 'first', attributes: [{ name: 'attr1' }] }, { name: 'second', attributes: [{ name: 'attr2' }] }];
const res = all.flatMap(x => x.attributes);
console.log(res);
Upvotes: 1
Reputation: 2933
You can also use spread operator for readability:
[...acc, ...el.attributes]
means that it is a new array, in the beginning of which are all acc
elements are placed, and after all el.attributes
elements are placed.
The arrow function in reduce
has no curly braces and the return keyword, in this form it returns [...acc, ...el.attributes]
:
const all = [{
'name': 'first',
'attributes': [{
'name': 'attr1'
}]
}, {
'name': 'second',
'attributes': [{
'name': 'attr2'
}]
}]
const res = all.reduce((acc, el) => [...acc, ...el.attributes], [])
console.log(res)
Upvotes: 1
Reputation: 781028
Use the .concat()
method to concatenate arrays, not +
.
const all = [{
'name': 'first',
'attributes': [{
'name': 'attr1'
}]
}, {
'name': 'second',
'attributes': [{
'name': 'attr2'
}]
}]
const res = all.reduce((acc, el) => acc.concat(el.attributes), [])
console.log(res)
Upvotes: 3