javascript - 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",
}
]
解决方案
非性能方法是
array1.filter(elm1 => {
return array2.find(elm2 => elm2.associatedID === elm1).length === 1
})
如果您的数组很大,您可以根据 id 和 associatedID 对两个数组进行排序并在它们上运行一个 for 循环以某种方式返回结果
推荐阅读
- python - 网络摄像头视频是黑白 Python 代码
- arrays - VBA 将工作表复制到新工作簿 - 带/不带公式
- python - 熊猫数据框输出不是预期的
- c++ - 有没有办法将 float** 数组转换为 Objective C 并显示这些值
- android - Android无法在特定文件夹中创建文件
- c - C中malloc的惯用宏?
- regex - 在使用 Slmgr /dlv 和正则表达式的文本字符串的第一个实例之后获取激活 ID 密钥?
- binary - 如果一行中不超过 M 个零/一,则有多少个具有 N 位的二进制数
- python - 如何以科学计数法获取 Chart js 标签
- javascript - 我如何创建一个可以接收和发送邮件到 Zimbra 服务器的模块