将嵌套集合属性拉入数组

问题描述 投票:0回答:4

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

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可以包含多个条目。

javascript arrays collections lodash
4个回答
1
投票

您可以像这样使用reduce

console.log(columns.reduce((agg, { sections }) => {
      return [...agg, ...sections.map(({ file }) => file)]
}, []));

它也适用于section数组中的多个文件。


0
投票

如果您在每个部分中只有一个部分,如上所示,则很简单:

map(columns, col => col.sections[0].file);

如果还有更多,请将文件数组减少为平面数组:

const res = columns.map(col => col.sections.map(section => section.file))
.reduce((all, current) => all.concat(current), []);

0
投票

您可以使用reduceconcat来创建所需的扁平阵列。

我不认为它真的需要看到你已经使用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 );
© www.soinside.com 2019 - 2024. All rights reserved.