NodeJS:从未包含在另一个数组中的数组中查找对象

时间:2017-08-25 12:54:51

标签: javascript node.js

我有两个对象数组:

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中的任何函数来实现这个或任何其他方式吗?

1 个答案:

答案 0 :(得分:3)

您可以将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; }