首页 > 解决方案 > Javascript中两个对象数组的Lodash过滤/交集

问题描述

我有两个对象数组。在第二个数组中,您可以从第一个数组中分配一个 id。如果第一个数组的 id 未在 array2 中关联,我如何过滤第一个数组以仅显示结果?我已经在 lodash 中尝试了一个过滤器的嵌套过滤器,以及一个 find 的过滤器,但它只是不起作用。

这是我尝试过的:

array1.filter(item => item.id === find(array2, { associatedID: item.id })[0].associatedID) 在过滤器中查找的第二次迭代。我尝试了类似的过滤方法而不是 find,但这也不起作用。在 find 函数中使用 item.id 是否存在问题,因为它是从父过滤器参数提供的?或者没有?

帮助?

const array1 = [{
  "id": "1",
  "name": "Test 1"
},
{
  "id": "2",
  "name": "Test 2",
}
{
  "id": "3",
  "name": "Test 3",
}
]

const array2 = [{
  "id": "12",
  "name": "Test 1",
  "associatedID": "1"
},
{
  "id": "22",
  "name": "Test 2",
  "associatedID": "2"
}
{
  "id": "32",
  "name": "Test 3",
}
]

标签: javascriptarraysobjectlodash

解决方案


非性能方法是

array1.filter(elm1 => {
  return array2.find(elm2 => elm2.associatedID === elm1).length === 1
})

如果您的数组很大,您可以根据 id 和 associatedID 对两个数组进行排序并在它们上运行一个 for 循环以某种方式返回结果


推荐阅读