gpt4 book ai didi

javascript - 如何从具有特定 id 的数组中获取对象与另一个数组编号进行比较

转载 作者:行者123 更新时间:2023-11-29 10:55:10 26 4
gpt4 key购买 nike

我需要比较来自 firstArray 和数组编号 (secondArray) 的 id 对象数组,并返回一个新数组,其中包含来自第一个数组的对象,其 id 编号存在于第二个数组中。

所以最后,我想要一个包含 id 为 39 和 41 的对象的新数组。

实际上我找到了这样的东西:

const result = arr2.filter(o => arr1.find(x => x.id === o));

const arr1 =
"blocks": [
{
"id": 1,
"functions": [ 0, 1 ]
},
{
"id": 39,
"functions": [ 0, 1, 3, 4 ]
},
{
"id": 41,
"functions": [ 0, 1 ]
}
]

const arr2 = [39, 41]

最佳答案

您可以使用 includes()在过滤过程中发挥作用。 Includes() 的工作方式类似于 in array 函数。

const arr1 =
[ {
"id": 1,
"functions": [ 0, 1 ] },
{
"id": 39,
"functions": [ 0, 1, 3, 4 ]
},
{
"id": 41,
"functions": [ 0, 1 ]
}
]

const arr2 = [39, 41]
const result = arr1.filter(o => arr2.includes(o.id));

console.log(result)

关于javascript - 如何从具有特定 id 的数组中获取对象与另一个数组编号进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59031380/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com