我有一个这样的嵌套数组:
const columns = [
{
sections: [
{
file: 'type-grid_1.svg',
featured: false,
dimensions: {
height: 4442,
width: 362
},
size: 'small'
}
]
}, {
sections: [
{
file: 'type-grid_2.svg',
featured: false,
dimensions: {
height: 4339,
width: 362
},
size: 'small'
}
]
}
];
我需要将所有file
值拉入数组,如下所示:
['type-grid_1.svg', 'type-grid_2.svg']
我试过这个,但它给了我数组的数组:
map(columns, (column) => map(column.sections, (section) => section.file))
建议?
UPDATE
忘记提及sections
可以包含多个条目。
您可以像这样使用reduce
:
console.log(columns.reduce((agg, { sections }) => {
return [...agg, ...sections.map(({ file }) => file)]
}, []));
它也适用于section数组中的多个文件。
如果您在每个部分中只有一个部分,如上所示,则很简单:
map(columns, col => col.sections[0].file);
如果还有更多,请将文件数组减少为平面数组:
const res = columns.map(col => col.sections.map(section => section.file))
.reduce((all, current) => all.concat(current), []);
我不认为它真的需要lodash看到你已经使用const
作为变量声明,所以你可能已经在使用某些版本的ES6。如果图书馆有特殊需要,请随时更新您的开场白。
const columns = [{
sections: [{
file: 'type-grid_1.svg',
featured: false,
dimensions: {
height: 4442,
width: 362
},
size: 'small'
}]
}, {
sections: [{
file: 'type-grid_2.svg',
featured: false,
dimensions: {
height: 4339,
width: 362
},
size: 'small'
}]
}];
const result = columns.reduce( (current, item) => current.concat( item.sections.map( section => section.file ) ), []);
console.log( result );