gpt4 book ai didi

javascript - reactjs 如何过滤/检查数组中的任何对象是否存在于另一个对象数组中?

转载 作者:行者123 更新时间:2023-12-03 07:05:06 25 4
gpt4 key购买 nike

我在尝试实现某些条件渲染时遇到了问题。这是上下文:

数据:

groups_a : [
{id:1} ,
{id:2}
]

groups_b : [
{id:1} ,
{id:3}
]

条件:

我想检查 groups_b 中的每个项目,它们是否存在于 groups_a 中。所以在这种情况下,条件应该返回 true 因为 groups_b 有 id:1 groups_a 也是如此

JSX:

            {###the condition ##
?
<Button>Approve</Button>
:
null
}

最佳答案

你可以假设 groupA/groupB 是对象数组

const groupA = [{id:1}, {id:3}, {id:4}];
const groupB = [{id:1}, {id:3}];

const boolean = groupB.every(obj => groupA.find(aObj => obj.id === aObj.id));
console.log('Method 1:', boolean)
// this will be true if every object in B is included in A

// If these are extremely large arrays you can improve performance by converting groupA into obj, and then checking by that object

const groupAHashMap = groupA.reduce((acc, cur) => ({...acc, [cur.id]: true}), {});
const boolean2 = groupB.every(obj => groupAHashMap[obj.id]);
console.log('Method 2:', boolean2)

关于javascript - reactjs 如何过滤/检查数组中的任何对象是否存在于另一个对象数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62129058/

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