首页 > 解决方案 > 对象数组中的连接数组

问题描述

我构建了这个数组:

const array = [
  {
    title: 'something',
    list: ['a', 'b', 'c', 'd']
  },
  {
    title: 'dog',
    list: ['aa']
  },
  {
    title: 'cat',
    list: ['aaa', 'b', 'cccc']
  },
  {
    title: 'apple',
    list: [],
  }
]

我想要一个包含其他数组中所有值的数组,所以:

const res = ['a', 'b', 'c', 'd', 'aa', 'aaa', 'b', 'cccc']

我可以这样做吗?我可以使用concat,但是如何使用?

标签: javascriptarraysobjectconcat

解决方案


您可以减少数组以展平属性。

const
    array = [{ title: 'something', list: ['a', 'b', 'c', 'd'] }, { title: 'dog', list: ['aa'] }, { title: 'cat', list: ['aaa', 'b', 'cccc'] }, { title: 'apple', list: [] }],
    list = array.reduce((r, { list }) => [...r, ...list], []);

console.log(list);

或采取也许即将到来flatMap的。

const
    array = [{ title: 'something', list: ['a', 'b', 'c', 'd'] }, { title: 'dog', list: ['aa'] }, { title: 'cat', list: ['aaa', 'b', 'cccc'] }, { title: 'apple', list: [] }],
    list = array.flatMap(({ list }) => list);

console.log(list);


推荐阅读