我有两个数组:
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,并将Employrol数组EmployeeId中的注册:true添加到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;
}
);
}
});
我在做错了什么?我该怎么做?
答案 0 :(得分:1)
试试这个
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);
员工随后将包含已注册或未在您的控制台中尝试此操作
答案 1 :(得分:1)
您的代码存在的问题是,执行if (arrayItem.UserGroupId === GroupId) {
时,相关员工会将enrolled
更改为true
,但执行此检查的else
部分时,它会覆盖if
条件部分所做的更改。
试试这个。
UserGroupUser = [{Id:"1",UserId:"2",UserGroupId:"1"},
{Id:"2",UserId:"3",UserGroupId:"1"},
{Id:"3",UserId:"4",UserGroupId:"2"}];
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 = "1";
Employee.map(function (emp) {
emp.enrolled = false;
});
UserGroupUser.forEach(function (arrayItem) {
if (arrayItem.UserGroupId === GroupId) {
Employee.map(function (emp) {
if (arrayItem.UserId === emp.EmployeeId) {
emp.enrolled = true;
}
});
}
});
console.log(Employee);