我有两个对象数组:
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中的任何函数来实现这个或任何其他方式吗?
答案 0 :(得分:3)
您可以将Set
与Array#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; }