gpt4 book ai didi

javascript - Node : Find object from array not contained in another array

转载 作者:搜寻专家 更新时间:2023-10-31 23:45:29 27 4
gpt4 key购买 nike

我有两个对象数组:

var existingUsers1 = [];
existingUsers1.push({
"userName": "A",
"departmentId": "1"
});
existingUsers1.push({
"userName": "B",
"departmentId": "1"
});
existingUsers1.push({
"userName": "C",
"departmentId": "1"
});
existingUsers1.push({
"userName": "D",
"departmentId": "1"
});

var existingUsers2 = [];
existingUsers2.push({
"userName": "A",
"departmentId": "1"
});
existingUsers2.push({
"userName": "B",
"departmentId": "1"
});

我需要从 existingUsers1 中找到 existingUsers2 中不存在的对象。我可以使用 nodeJS 中的任何函数来实现此目的或任何其他方式吗?

最佳答案

你可以使用 SetArray#filter .

var existingUsers1 = [{ userName: "A", departmentId: "1" }, { userName: "B", departmentId: "1" }, { userName: "C", departmentId: "1" }, { userName: "D", departmentId: "1" }],
existingUsers2 = [{ userName: "A", departmentId: "1" }, { userName: "B", departmentId: "1" }],
hash = new Set(existingUsers2.map(o => o.userName)),
result = existingUsers1.filter(o => !hash.has(o.userName));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - Node : Find object from array not contained in another array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45881935/

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