亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

用另一個對象數組過濾對象數組,并為匹配的對象添加額外的鍵

用另一個對象數組過濾對象數組,并為匹配的對象添加額外的鍵

UYOU 2021-05-07 14:44:50
我有以下兩個數組,我想獲取第二個數組,但匹配的對象應包含一個額外的鍵“ 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)               }             }          }
查看完整描述

3 回答

?
瀟瀟雨雨

TA貢獻1833條經驗 獲得超4個贊

這應該工作:


var ans = secondArray.map(s=> {

var match = firstArray.find(f=> f.id === s.id);

if(match) s['select'] = true;

else s['select'] = false;

return s;

})


查看完整回答
反對 回復 2021-05-13
  • 3 回答
  • 0 關注
  • 323 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號