我想返回一个deconsturcted数组,所以我只返回te返回数组中的单个元素而不是数组。
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);

所以我想使用链式地图函数在item.components
中创建一个包含所有元素的数组。这可能吗?好像我无法解构每个项目的数组。
答案 0 :(得分:2)
Array.prototype.reduce
似乎是在此上下文中使用的正确方法。
const test = data.reduce( (result, current) => result.concat(current.components) , []);
console.log('test', test);
输出
test [ { id: 1, name: 'yanick' },
{ id: 2, name: 'ronald' },
{ id: 4, name: 'nicky' },
{ id: 3, name: 'casper' } ]
答案 1 :(得分:1)
使用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);

答案 2 :(得分:0)
要将数据合并为单个数组,您可以将reduce
与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 test = data
.map(item => {
return item.components;
}).reduce((res, item) => {
return res.concat(item);
}, []);
console.log('test', test);