简体   繁体   English

使用es6 map返回对象中的解构数组

[英]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 . 因此,我想使用链接映射函数来创建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. Array.prototype.reduce似乎是在此上下文中使用的正确方法。

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() : 使用Array.map()获取components ,并通过展开到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. 要将数据组合到单个数组中,可以将reduceconcat结合使用,以创建单个结果数组。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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