javascript - 用另一个对象数组过滤对象数组,并为匹配的对象添加额外的键

标签 javascript arrays

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

最佳答案

您可以创建一个 Set firstArray 中存在的所有 id。然后使用 forEach 遍历 secondArray 并根据集合 has 是否添加 select 值。身份证

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)

关于javascript - 用另一个对象数组过滤对象数组,并为匹配的对象添加额外的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55866218/

相关文章:

javascript - R Shiny : Check a Regular expression in textInput on UI

javascript - 变量范围和使用 qUnit 进行测试

javascript - 将整数字符串拆分为数组 - 元素无法被识别

arrays - Swift - 向字典内的数组添加值

javascript - 如何计算一个项目在数组中的次数

javascript - 如何使用 Google Apps 脚本在电子邮件主题中使用表情符号?

javascript - 将 Backbone 模型或导出的 json 对象传递给像 mustache 这样的模板系统

javascript - Modal 上的 Bootstrap 叠加控件 - 滚动问题

c - 如何对数组指向的区域内存进行逻辑或

java - 分割字符串java返回值