首页 > 解决方案 > 用另一个对象数组过滤对象数组,并为匹配的对象添加额外的键

问题描述

我有以下两个数组,我想获得第二个数组,但匹配的对象应该包含一个额外的键“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)
               }
             }
          }

标签: javascriptarrays

解决方案


您可以创建Set所有 id 中存在的firstArray. 然后根据是否设置id循环secondArray使用forEach和添加值selecthas

let firstArray=[{id:-1,type:"group"},{id:-2,type:"group"}],
    secondArray=[{id:-3,type:"group"},{id:-2,type:"group"},{id:-1,type:"group"}];

const ids = new Set(firstArray.map(a => a.id));
secondArray.forEach(a => a.select = ids.has(a.id))

console.log(secondArray)


推荐阅读