javascript - 按 id 数组过滤对象数组

标签 javascript arrays angular object

我有一个包含服务 ID 的数组 activeIds,还有另一个包含服务对象的数组 servicesList

例子:-

activeIds = [202, 204]
serviceList = [{  
                "id":201,
                "title":"a"
               },
               {  
                "id":202,
                "title":"a"
               },
               {  
                "id":203,
                "title":"c"
               },
               {  
                "id":204,
                "title":"d"
               },
               {  
                "id":205,
                "title":"e"
               }];

我想要其 ID 不属于第一个数组的所有服务 (obj),即 activeIds。从上面的示例代码我想要 ids 201,203,205 的服务对象

最终输出 -

expectedArray = [{  
                "id":201,
                "title":"a"
               },
               {  
                "id":203,
                "title":"c"
               },
               {  
                "id":205,
                "title":"e"
               }];

这是我的代码尝试。但这根本不正确。请帮助-

    const activeIds = e; // [202, 204]
    const obj = [];
    this.serviceList.map((s: IService) => {
        activeIds.map((id: number) => {
            if (id !== s.id) {
                obj.push(s);
            }
        });
    });

最佳答案

您可以简单地使用 array.filter indexOf 检查下一个数组中的匹配元素。

var arr = serviceList.filter(item => activeIds.indexOf(item.id) === -1);

演示

let activeIds = [202, 204]
let serviceList = [{  
                "id":201,
                "title":"a"
               },
               {  
                "id":202,
                "title":"a"
               },
               {  
                "id":203,
                "title":"c"
               },
               {  
                "id":204,
                "title":"d"
               },
               {  
                "id":205,
                "title":"e"
               }];


let  arr = serviceList.filter(function(item){
      return activeIds.indexOf(item.id) === -1;
    });
    
console.log(arr);

关于javascript - 按 id 数组过滤对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48844452/

相关文章:

asp.net 4.0 webforms - 如何以简单的方式将 ContentPlaceHolder1_ 排除在客户端 ID 之外?

php - 稳定的 uasort - 为什么顺序被颠倒了?

javascript - 错误 : The loader in . css 未在 Angular 12.1.1 中返回字符串

Angular NgRx-仅在首次调用时才继续轮询服务的效果

javascript - 在 Google Ajax 中显示页面加载微调器

javascript - JS 当用户点击显示不同的颜色

javascript - 如何过滤以@开头的单词形成 Angular 2中的字符串

java - 如何检查数组是否已满,如果未满则添加到它?

c - 在结构数组中查找值

javascript - Angular 6 : unable to make http request