javascript - 展平数组内部的数组
问题描述
我有一个对象数组,每个对象都有一个名为 app 的属性,如果检查数组具有相同的应用程序,我需要使用另一个数组进行过滤,然后过滤并仅获取该应用程序。
我能够得到它,但我的问题是我得到了嵌套数组,我需要得到一个包含 4 个对象的数组。
请看下面的代码。还有其他方法可以获得预期的输出。
let data = [{
app: "test1",
key: 1
}, {
app: "test2",
key: 2
}, {
app: "test1",
key: 3
}, {
app: "test2",
key: 3
}]
let checkArr = ["test1", "test2", "test3"]
let result = checkArr.map(ch => data.filter(da => da.app === ch))
console.log(result)
预期产出
[{
"app": "test1",
"key": 1
}, {
"app": "test1",
"key": 3
}, {
"app": "test2",
"key": 2
}, {
"app": "test2",
"key": 3
}]
解决方案
您可以使用Array.flatMap()
(IE/Edge 不支持):
let data = [{app: "test1", key: 1}, {app: "test2", key:2}, {app: "test1", key:3}, {app: "test2", key:3}]
let checkArr = ["test1", "test2", "test3"]
let result = checkArr.flatMap(ch => data.filter(da => da.app === ch))
console.log(result)
或通过展开成扁平化Array.concat()
:
let data = [{app: "test1", key: 1}, {app: "test2", key:2}, {app: "test1", key:3}, {app: "test2", key:3}]
let checkArr = ["test1", "test2", "test3"]
let result = [].concat(...checkArr.map(ch => data.filter(da => da.app === ch)))
console.log(result)
推荐阅读
- python - 如何在读取 excel 文件时直接解析数据框中的日期,而不是使用 parse_dates 参数?
- c# - 使用 for 循环检查字符串定义的数组元素
- java - 解析传入的短信 Android (API 26)
- c# - 发布后检索具有多个列表对象的 ViewModel
- mysql - MySQL优化几何查询
- shell - 当我在 docker 容器中执行 shell 脚本时,错误是“没有这样的文件或目录”
- gridview - 如何在 yii2 中将复选框列添加到现有的 gridview 列?
- biztalk - 用于词汇表的 BizTalk BRE 实用程序
- javascript - getImageData() 数组在角度 5 中返回全 0
- angular - 如何防止为 prod 编译调试代码