javascript - 在对象数组中连接数组

标签 javascript arrays object concatenation

我构建这个数组:

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 但如何使用呢?

最佳答案

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

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);

关于javascript - 在对象数组中连接数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54463977/

相关文章:

python - 如何将 python 函数/类/模块对象转换为 python 代码对象

javascript - 当通过更改 css 使 Div 可见时,该 div 上的事件将发生多次

c++ - 创建类的二维数组

javascript - 如何在javascript数组中添加Java对象?

arrays - 将数组合并到一种状态react-native

perl - 如何在 Perl 中以完全相同的方式对两个数组进行洗牌?

javascript - (Javascript/RaphaelJS) 如何将变量附加到新数组中的新对象?

javascript - 将嵌套对象的每个对象的索引设置为属性

javascript - 向下滚动页面时多次更改背景颜色

php - 如何在表单提交时将带有 <option> 的表单元素 <select> 中的数据提取到 php 中?