gpt4 book ai didi

javascript - 在javascript和react中比较两个数组并在此基础上过滤一个数组

转载 作者:行者123 更新时间:2023-12-02 19:16:40 25 4
gpt4 key购买 nike

我正在尝试比较两个对象数组,如下所示:

const obj1 = [
{name:"Mark"},
{name:"David"},
{name:"Ellie"},
{name:"Zuank"},
{name:"Philip"},
{name:"Den"},
]
const obj2 = [
{name:"Mark"},
{name:"David"},
{name:"Zuank"},
{name:"Philip"},
]

我想检查第二个对象中是否存在每个对象的名称。如果是,我想将该对象推送到一个新数组,并将名为“Matched”的新属性添加到每个值为“true”的对象。否则,Matched 属性将为 false。这是我想要达到的最终结果:

  const res = [
{ name: "Mark", matched: true },
{ name: "David", matched: true },
{ name: "Ellie", matched: false },
{ name: "Zuank", matched: true },
{ name: "Philip", matched: true },
{ name: "Den", matched: false },
]

--编辑这是我到目前为止所尝试过的:

obj1.map((element, index) => {
if (obj2[index].name === element.name) {
resArr.push({ name: element.name, matched: true })
}
else {
resArr.push({ name: element.name, matched: false })
}
})

最佳答案

您可以在 obj2 上使用 some 执行 map obj1 来检查 obj1 元素是否位于 obj2

const obj1 = [
{ name: "Mark" },
{ name: "David" },
{ name: "Ellie" },
{ name: "Zuank" },
{ name: "Philip" },
{ name: "Den" },
]

const obj2 = [
{ name: "Mark" },
{ name: "David" },
{ name: "Zuank" },
{ name: "Philip" },
]

const res = obj1.map((el1) => ({
name: el1.name,
match: obj2.some((el2) => el2.name === el1.name),
}))

console.log(res)

关于javascript - 在javascript和react中比较两个数组并在此基础上过滤一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63618168/

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