有两个数组包含如下对象:
var departmentArray=[{DepartmentId:1,DeparmentTitle:Dept1},{DepartmentId:2,DeparmentTitle:Dept2},{DepartmentId:3,DeparmentTitle:Dept3}];
var employeesArray = [{EmpId:1,EmpName:Raj,DepartmentId:1},{EmpId:2,EmpName:Ravi,DepartmentId:1},{EmpId:3,EmpName:Ram,DepartmentId:1},{EmpId:4,EmpName:Rajesh,DepartmentId:2},{EmpId:5,EmpName:Rahim,DepartmentId:2}];
var departmentAndEmployeeDetails = {
this.DepartmentId = 0;
this.DepartmentTitle = '';
this.EmployeeId = 0;
this.EmployeeName = '';
}
var departmentAndEmployeeArray = [];
for(var i=0;i<departmentArray.length;i++)
{
var currentEmployees = [];
var empDepartmentItem = new departmentAndEmployeeDetails();
empDepartmentItem.DepartmentId = departmentArray[i].DepartmentId;
empDepartmentItem.DepartmentTitle = departmentArray[i].DeparmentTitle;
currentEmployees = $.grep(employeesArray,function(empItem,index){
return (empItem.Department==departmentArray[i].DepartmentId);
});
if(currentEmployees.length>0)
{
for(var j=0;j<currentEmployees.length;j++)
{
empDepartmentItem.EmployeeId = currentEmployees[j].EmpId;
empDepartmentItem.EmployeeName = currentEmployees[j].EmpName;
departmentAndEmployeeArray.push(empDepartmentItem);
}
}
else
{
departmentAndEmployeeArray.push(empDepartmentItem);
}
}
执行上面的代码后,得到以下结果: departmentAndEmployeeArray包含以下项目。
departmentAnEmplyoeeArray = [{DepartmentId:1,DepartmentTitle:Dept1,EmployeeId:3,EmployeeName:Emp3}, {DepartmentId:1,DepartmentTitle:Dept1,EmployeeId:3,EmployeeName:Emp3}, {DepartmentId:1,DepartmentTitle:Dept1,EmployeeId:3,EmployeeName:Emp3}, {DepartmentId:2,DepartmentTitle:Dept2,EmployeeId:5,EmployeeName:Emp5}, {DepartmentId:2,DepartmentTitle:Dept2,EmployeeId:5,EmployeeName:Emp5}];
但预期结果是跟随一个。
departmentAnEmplyoeeArray = [{DepartmentId:1,DepartmentTitle:Dept1,EmployeeId:1,EmployeeName:Emp1}, {DepartmentId:1,DepartmentTitle:Dept1,EmployeeId:2,EmployeeName:Emp2}, {DepartmentId:1,DepartmentTitle:Dept1,EmployeeId:3,EmployeeName:Emp3}, {DepartmentId:2,DepartmentTitle:Dept2,EmployeeId:4,EmployeeName:Emp4}, {DepartmentId:2,DepartmentTitle:Dept2,EmployeeId:5,EmployeeName:Emp5}];
实际上,这里发生的是,在currentEmployees数组循环中,最后一个员工详细信息将在将数据推送到数组后替换先前的员工详细信息。
当第二次迭代在departmentArray中发生并将元素推入结果数组时,之前存在的项值被最后一项值替换。
先感谢您的帮助
答案 0 :(得分:1)
由于您正在循环中需要在该循环中使用新对象,因此只需使用object.assign创建该对象的克隆。 现在你只是在每次迭代时将相同的对象推入循环
for(var j=0;j<currentEmployees.length;j++)
{
let empDeptItem = Object.assign({}, empDepartmentItem);
empDeptItem.EmployeeId = currentEmployees[j].EmpId;
empDeptItem.EmployeeName = currentEmployees[j].EmpName;
departmentAndEmployeeArray.push(empDeptItem);
}
答案 1 :(得分:0)
@JoshKisb的答案在某些浏览器中运行正常,但在IE浏览器中却没有。因此,要在所有浏览器中使用此功能,我们可以使用 $。extend 代替 jQuery 中的 Object.assign ,如下所示:
for(var j=0;j<currentEmployees.length;j++)
{
let empDeptItem = $.extend({}, empDepartmentItem);
empDeptItem.EmployeeId = currentEmployees[j].EmpId;
empDeptItem.EmployeeName = currentEmployees[j].EmpName;
departmentAndEmployeeArray.push(empDeptItem);
}
希望这有助于他人。