alex
alex

Reputation: 147

How to combine objects of arrays that are in different objects

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

Answers (4)

blex
blex

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

tsu
tsu

Reputation: 1251

One line code for you

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

Upvotes: 0

IvanD
IvanD

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

Barmar
Barmar

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

Related Questions