按ID数组过滤对象数组 [英] Filter array of objects by array of ids
本文介绍了按ID数组过滤对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含服务ID的数组activeIds
,还有另一个包含服务对象的数组servicesList
.
I have an array activeIds
of ids of services and there is another array servicesList
which contains objects of services.
示例:-
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不属于第一个数组即activeIds
的所有服务(obj).在上面的示例代码中,我希望ID为201,203,205的服务obj
I want all the services(obj) whose ids are not a part of the first array i.e., activeIds
. From the above example code I want service obj of ids 201,203,205
最终输出-
expectedArray = [{
"id":201,
"title":"a"
},
{
"id":203,
"title":"c"
},
{
"id":205,
"title":"e"
}];
这是我尝试编码的尝试.但这是完全不正确的.请帮助-
Here is my attempt to code. But it is not correct at all. Please help-
const activeIds = e; // [202, 204]
const obj = [];
this.serviceList.map((s: IService) => {
activeIds.map((id: number) => {
if (id !== s.id) {
obj.push(s);
}
});
});
推荐答案
您可以简单地使用 indexOf
来检查下一个数组中的匹配元素.
You can simply use array.filter
with indexOf
to check the matching element in the next array.
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);
这篇关于按ID数组过滤对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文