按ID数组过滤对象数组

时间:2018-02-17 18:20:14

标签: 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"
               }];

我想要所有的服务(obj),其id不是第一个数组的一部分,即activeIds。从上面的示例代码我想要服务obj的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);
            }
        });
    });

4 个答案:

答案 0 :(得分:5)

您可以使用filterincludes方法执行此操作。

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

const result = serviceList.filter(({id}) => !activeIds.includes(id));
console.log(result)

答案 1 :(得分:2)

您只需使用 array.filter indexOf 一起检查下一个数组中的匹配元素。

var arr = serviceList.filter(function(item){
  return 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);

答案 2 :(得分:2)

使用filter&amp; indexOf方法。indexOf将检查activeIds数组中是否存在当前ID

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

var filteredArray = serviceList.filter(function(item) {
  return activeIds.indexOf(item.id) === -1

});

console.log(filteredArray)

答案 3 :(得分:2)

您可以组合indexOf来检查当前ID是否在活动阵列上并过滤数组。