0

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.

2
  • Why not just map? Commented Dec 22, 2020 at 20:09
  • 1
    @evolutionxbox Because that would return an Array of Arrays. flatMap, though, would work Commented Dec 22, 2020 at 20:11

4 Answers 4

3

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

1

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);

Comments

0

One line code for you

[].concat(...all.map(item => item.attributes ))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.