将嵌套集合属性拉入数组

时间:2017-12-20 15:11:57

标签: javascript arrays collections lodash

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

formatters.mmddyyyy

我需要将所有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)) 可以包含多个条目。

4 个答案:

答案 0 :(得分:2)

只有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>

答案 1 :(得分:1)

你可以这样使用-bash: /opt/local/bin/pkg-config: No such file or directory

reduce

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

答案 2 :(得分: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), []);

答案 3 :(得分:0)

您可以使用reduceconcat来创建所需的拼合数组。

我不认为确实需要const作为变量声明,因此您可能已经在使用某些版本的ES6。如果图书馆有特殊需要,请随时更新您的开场白。

&#13;
&#13;
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 );
&#13;
&#13;
&#13;