我有以下兩個數組,我想獲取第二個數組,但匹配的對象應包含一個額外的鍵“ select”:true,而不匹配的對象應包含“ select”:false。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) } } }
用另一個對象數組過濾對象數組,并為匹配的對象添加額外的鍵
UYOU
2021-05-07 14:44:50