JS将元素推送到数组(如果它不存在),然后重新计算数组

时间:2018-04-21 20:12:52

标签: javascript arrays ecmascript-6 iteration

我正在使用以下内容。

const employeesByDepartment = {};

employeesArray.forEach((employee) => {

    if (!(employeesByDepartment[employee.department])) {
        employeesByDepartment[employee.department] = {};
        employeesByDepartment[employee.department].managers = [];
        employeesByDepartment[employee.department].members = [];
    }

    let thisManagerAlreadyAdded = false;

    // PROBLEM ON NEXT LINE
    employeesByDepartment[employee.department].managers.forEach((manager) => {
        if (manager.id === employee.manager) {
            thisManagerAlreadyAdded = true;
        }
    });

    if (thisManagerAlreadyAdded === false) {
        employeesByDepartment[employee.department].managers
            .push(ReturnOneUser(employee.manager));
    }
});

问题:没有找到任何经理在阵列中,所以他们都被添加了。也就是说,永远不会到达此块中的表达式。

employeesByDepartment[employee.department].managers.forEach((manager)

在我的测试中,该数组的length始终为0。因此,我假设每次执行forEach时,JS解释器(Node.js)都不会重新检查数组。到目前为止,我还尝试了数组indexOf方法和for循环,但是在数组中找不到任何管理器。

那么,如何添加未找到的管理器,然后为下一个管理器重新评估该数组呢?

2 个答案:

答案 0 :(得分:0)

不会移动条件来解决你的问题吗?

const employeesByDepartment = {};

employeesArray.forEach((employee) => {
  let thisManagerAlreadyAdded = false;
    if (!(employeesByDepartment[employee.department])) {
        employeesByDepartment[employee.department] = {};
        employeesByDepartment[employee.department].managers = [];
        employeesByDepartment[employee.department].members = [];
    }

  if (!thisManagerAlreadyAdded) {
        employeesByDepartment[employee.department].managers
            .push(ReturnOneUser(employee.manager));
    }

    // MOVE IT HERE
    employeesByDepartment[employee.department].managers.forEach((manager) => {
        if (manager.id === employee.manager) {
            thisManagerAlreadyAdded = true;
        }
    });
});

答案 1 :(得分:0)

您可以使用.find检查用户是否已存在于某个阵列中。

即,如果<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <title>404 Not Found</title> <h1>Not Found</h1> <p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p> 是当前数组,则使用managers将始终通过整个数组并检查结果。这是考虑.findmanager.id都是字符串。

employee.manager

如果您在开始时使用!!managers.find(manager => manager.id === employee.manager); ,它将返回一个布尔值。您不需要使用任何!!样式代码。

所以你可以简单地使用它,

thisManagerAlreadyAdded