listOne: [
{
id: 1,
compId: 11,
active: false,
},
{
id: 2,
compId: 22,
active: false,
},
{
id: 3,
compId: 33,
active: false,
},
]
listTwo: [
{
id: 1,
compId: 11,
active: true,
},
{
id: 2,
compId: 33,
active: false,
},
]
我有两个json,这里是如何与 compId 键进行比较,如果 compId,如何从 listTwo 中更新 listOne 中的活动密钥相同。
在AngularJs中,我尝试使用此相关链接for AngularJs
但是如何通过Typescript与Angular 6集成。
预期输出为
listOne: [
{
id: 1,
compId: 11,
active: true,
},
{
id: 2,
compId: 22,
active: false,
},
{
id: 3,
compId: 33,
active: false,
},
]
答案 0 :(得分:1)
您可以像这样使用地图和过滤器
listOne = listOne.map(item => {
let exist = listTwo.filter(c=>c.compId == item.compId)[0];
if(exist != undefined){
item.active = exist.active;
return item;
}else{
return item;
}
});
let listOne= [
{
id: 1,
compId: 11,
active: false,
},
{
id: 2,
compId: 22,
active: false,
},
{
id: 3,
compId: 33,
active: false,
},
]
let listTwo= [
{
id: 1,
compId: 11,
active: true,
},
{
id: 2,
compId: 33,
active: false,
},
]
//let arr3 = [];
listOne = listOne.map(item => {
let exist = listTwo.filter(c=>c.compId == item.compId)[0];
if(exist != undefined){
//item.id = exist.id;
item.active = exist.active;
return item;
}else{
return item;
}
});
console.log(listOne);
答案 1 :(得分:0)
尝试一下
// Iterate over list one
for(let item of this.listOne){
// Check if the item exist in list two
if(this.listTwo.find(i=>i.compId==item.compId)){
// Update key
item.active = this.listTwo.find(i=>i.compId==item.compId).active;
}
}
答案 2 :(得分:0)
我试图找到问题的解决方案。 因此,我们需要迭代两个 for 来检查每个数据,如下所示。 并且需要根据需要更换
for (const s of listOne) {
for (const r of listTwo) {
if (s.compId === r.compId) {
s.active = r.active;
break;
}
}
}