javascript - 对象数组中的连接数组
问题描述
我构建了这个数组:
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);
推荐阅读
- python - 将渲染页面从 Selenium 传递给 Scrapy
- ionic4 - 如果尚未确认,我如何知道当前在多列离子选择器的列中选择了哪些元素?
- sql - Pyspark:迭代数据框中的组
- angular - UglifyJsPlugin 不会在 Angular 构建中保留类和函数名称
- node.js - 错误:损坏的 zip:找不到中央目录的结尾 - XLSX Populate
- visual-studio - 远程调试错误:无法附加到进程。调用的对象已与其客户端断开连接
- qt - 在 Qt 中打开街道地图不返回带有许多参数的地址
- javascript - 在 HTML 中插入了意外的空白元素
- c# - 如何添加扩展方法
- excel - 字符串操作-我怎么说excel“如果字母“v”和一个数字一起出现”?