首页 > 解决方案 > 展平数组内部的数组

问题描述

我有一个对象数组,每个对象都有一个名为 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
}]

标签: javascriptarrays

解决方案


您可以使用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)


推荐阅读