我有两个数组:
UserGroupUser[{Id:"1",UserId:"2",UserGroupId"1"},
{Id:"2",UserId:"3",UserGroupId"1"},
{Id:"3",UserId:"4",UserGroupId"2"}]
UserGroupId 将具有 1、2、3 等值。
Employee[{EmployeeId:"1", EmpName:"John", Email:"john@example.com"},
{EmployeeId:"2", EmpName:"Mary", Email:"Mary@example.com"},
{EmployeeId:"3", EmpName:"Sarah", Email:"Sarah@example.com"},
{EmployeeId:"4", EmpName:"Jake", Email:"Jake@example.com"} ]
我将在变量 GroupId 中存储一个数字,例如 GroupId=1 我想要做的是检查 UserGroupUser 表,如果 GroupId 1 与关键 UserGroupId 的任何行匹配,并且如果每个 UserId 都有匹配,则 Employee 表中匹配的相应 EmployeeId 意味着我添加一个新的名为 enrolled=true 的元素。否则,如果不匹配,则向 Employee enrolled=false 添加一个元素。
例如:
如果 GroupId =1 ,那么我想获取 UserGroupUser 数组中 UserGroupId 为 1 的用户的 userId ,并将 enrolled:true 添加到 Employee 数组 EmployeeId 中,以与 UserId 对应。
这就是我尝试做的事情..
UserGroupUser.forEach(function (arrayItem) {
if (arrayItem.UserGroupId === GroupId) {
result = Employee.map(function (a, index, array) {
while (arrayItem.UserId === a.EmployeeNo) {
a.enrolled = true;
}
return a;
}
);
}
else {
result = Employee.map(function (a, index, array) {
a.enrolled = false;
return a;
}
);
}
});
我做错了什么?我应该怎么做?
最佳答案
试试这个
var userGroup = [{Id:"1",UserId:"2",UserGroupId:"1"},
{Id:"2",UserId:"3",UserGroupId:"1"},
{Id:"3",UserId:"4",UserGroupId:"2"}]
var employees = [{EmployeeId:"1", EmpName:"John", Email:"john@example.com"},
{EmployeeId:"2", EmpName:"Mary", Email:"Mary@example.com"},
{EmployeeId:"3", EmpName:"Sarah", Email:"Sarah@example.com"},
{EmployeeId:"4", EmpName:"Jake", Email:"Jake@example.com"} ]
employees.forEach(function(item){
var found = userGroup.filter(i=>i.UserId==item.Id);
if(found.length>0)
item.enrolled = true
else
item.enrolled = false
})
console.log(employees);
然后,员工将包含注册或不在您的控制台中尝试此操作
关于javascript - 如何在检查另一个数组后向数组添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43774348/