gpt4 book ai didi

javascript - 将嵌套集合属性拉入数组

转载 作者:行者123 更新时间:2023-11-28 17:41:12 25 4
gpt4 key购买 nike

我有一个像这样的嵌套数组:

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#concatarray 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com