简体   繁体   中英

Return deconstructed array in object with es6 map

I want to return a deconsturcted array so I only get single element in te returned array instead of array.

 const data = [ { title: 'amsterdam', components: [ { id: 1, name: 'yanick', }, { id: 2, name: 'ronald', }, ], }, { title: 'rotterdam', components: [ { id: 4, name: 'nicky', }, { id: 3, name: 'casper', }, ], }, ]; const test = data .map(item => { console.log(item.components); return item.components; }).map(array => { // how to get comibned components here? // it can't use ...item.components (deconstructing or something) }); console.log('test', test); 

So I want to use chained map functions to create one array of all elements in item.components . Is this possible? Seems like I can't deconstruct the array of each item.

Array.prototype.reduce seems like the correct method to use in this context.

const test = data.reduce( (result, current) => result.concat(current.components) , []);

console.log('test', test);

Output

test [ { id: 1, name: 'yanick' },
  { id: 2, name: 'ronald' },
  { id: 4, name: 'nicky' },
  { id: 3, name: 'casper' } ]

Get the components with Array.map() , and flatten by spreading into Array.concat() :

 const data = [{"title":"amsterdam","components":[{"id":1,"name":"yanick"},{"id":2,"name":"ronald"}]},{"title":"rotterdam","components":[{"id":4,"name":"nicky"},{"id":3,"name":"casper"}]}]; const result = [].concat(...data.map(o => o.components)); console.log(result); 

To get data combined into single array you can use reduce in combination with concat that will create a single array of results.

 const data = [ { title: 'amsterdam', components: [ { id: 1, name: 'yanick', }, { id: 2, name: 'ronald', }, ], }, { title: 'rotterdam', components: [ { id: 4, name: 'nicky', }, { id: 3, name: 'casper', }, ], }, ]; const test = data .map(item => { return item.components; }).reduce((res, item) => { return res.concat(item); }, []); console.log('test', test); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM