我有一个像这样的嵌套数组:
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))
建议?
更新
忘记提及部分
可以包含多个条目。
最佳答案
仅使用 ES6,您就可以使用嵌套进行迭代 Array#map ,并使用Array#concat与 array spread压平:
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 = [].concat(...columns.map(({ sections }) => sections.map((section) => section.file)));
console.log(result);
使用 lodash,您可以使用 flatMap()
:
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 { map, flatMap } = _;
const result = flatMap(columns, (column) => map(column.sections, 'file'))
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
关于javascript - 将嵌套集合属性拉入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47909106/