【发布时间】:2019-05-05 17:35:01
【问题描述】:
我有以下两个数组,我想获得第二个数组,但是匹配的对象应该包含一个额外的键 "select" : true, 而不匹配的对象应该包含 "select" :错误。
var firstArray = [{id: -1, type: "group"},
{id: -2, type: "group"}];
var secondArray = [{id: -3, type: "group"},
{id: -2, type: "group"},
{id: -1, type: "group"}];
预期结果:
var expectedArray = [{id: -1, type: "group", select: true},
{id: -2, type: "group", select: true},
{id: -3, type: "group", select: false}];
我试过下面的代码:
for(var i=0;i<firstArray.length;i++){
for(var j=0;j<secondArray.length;j++){
console.log(firstArray[i].id,secondArray[j].id)
if(firstArray[i].id===secondArray[j].id){
if(secondArray[j].hasOwnProperty('select')){
secondArray[j].select=true;
// console.log('true select property',secondArray[j].select)
}
else{
secondArray[j].select=true;
// console.log('true adding new',secondArray[j].select)
}
}else{
secondArray[j]['select']=false;
// console.log('false not match',secondArray[j].select)
}
}
}
【问题讨论】:
-
@user11299053,当然,它有效,请为我的问题投票。
标签: javascript arrays