比较两个列表并将一个列表值更新为另一个angular5

时间:2018-11-06 14:58:29

标签: javascript angular

我有两个对象列表

列表1: TotalEmployers-

 [{EmployerId: 1,Name:"Rick", Checked :false}, {EmployerId: 2,Name:"John", Checked :false},{EmployerId: 3,Name:"Maddy", Checked :false}]

列表2: UpdatedEmployer

[{EmployerId: 1,Name:"Rick"},{EmployerId: 2,Name:"John"}]

如何基于list2中的记录将list1检查值更新为true

最终输出:

列表1: TotalEmployers-

[{EmployerId: 1,Name:"Rick", Checked :true}, {EmployerId: 2,Name:"John", Checked :true},{EmployerId: 3,Name:"Maddy", Checked :false}]

5 个答案:

答案 0 :(得分:2)

这可能是最紧凑的代码:

TotalEmployers.forEach(x => {
   x.Checked = UpdatedEmployer.some(y => y.EmployerId === x.EmployerId);
});

答案 1 :(得分:1)

尝试使用 map 运算符:

TotalEmployers.map(employee=> {
   return employee.Checked = UpdatedEmployer.some(cobay => cobay.EmployerId=== employee.EmployerId);
});

以下是您的案例的摘要:

TotalEmployers = [{EmployerId: 1,Name:"Rick", Checked :false}, {EmployerId: 2,Name:"John", Checked :false},{EmployerId: 3,Name:"Maddy", Checked :false}];

UpdatedEmployer = [{EmployerId: 1,Name:"Rick"},{EmployerId: 2,Name:"John"}];




TotalEmployers.map(employee=> {
   return employee.Checked = UpdatedEmployer.some(cobay => cobay.EmployerId=== employee.EmployerId);
});


console.log(TotalEmployers);

答案 2 :(得分:0)

如果TotalEmployers中的一名雇员包含ID,请通过UpdatedEmployer方法将其设置为true或false,从而遍历您的some

TotalEmployers.forEach(function(employee)
{        
    employee.checked = UpdatedEmployer.some(function (item) {
           return item.EmployerId == employee.EmployerId;
       });

})

答案 3 :(得分:0)

您可以使用Array.prototype.map遍历数组。如您在文档中所见,它返回一个新数组,并根据传递给它的回调函数对每个元素进行了修改。

TotalEmployers = TotalEmployers.map(e => {
   e.Checked = UpdatedEmployer.some(cobay => cobay.id === e.id);
});

答案 4 :(得分:0)

在javascript中使用Sets的另一种解决方案

        var failedCallsRequest = new CallListRequest
        {
            Status = "failed",
            StartTime = from,
            StartTimeComparison = ComparisonType.GreaterThanOrEqualTo,
            Count = _pageCount
        };

        var failedList = _client.ListCalls(failedCallsRequest).Calls.Where(c => c.Direction == "inbound").ToList();