[英]Filter array of objects by array of ids
I have an array activeIds
of ids of services and there is another array servicesList
which contains objects of services.我有一个数组activeIds
服务的IDS的还有另一个数组servicesList
其中包含服务的对象。
Example: -例子:-
activeIds = [202, 204]
serviceList = [{
"id":201,
"title":"a"
},
{
"id":202,
"title":"a"
},
{
"id":203,
"title":"c"
},
{
"id":204,
"title":"d"
},
{
"id":205,
"title":"e"
}];
I want all the services(obj) whose ids are not a part of the first array ie, activeIds
.我想要所有服务(obj),其 id 不是第一个数组的一部分,即activeIds
。 From the above example code I want service obj of ids 201,203,205从上面的示例代码中,我想要 ID 为 201,203,205 的服务对象
Final output -最终输出 -
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);
}
});
});
You can simply use array.filter
with indexOf
to check the matching element in the next array.您可以简单地使用带有indexOf
array.filter
来检查下一个数组中的匹配元素。
var arr = serviceList.filter(item => activeIds.indexOf(item.id) === -1);
DEMO演示
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);
You can do this with filter
and includes
methods.您可以使用filter
和includes
方法来做到这一点。
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)
Use filter
& indexOf
method.使用filter
& indexOf
方法。 indexOf
will check if the current id is present in activeIds
array indexOf
将检查当前 id 是否存在于activeIds
数组中
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)
您可以结合indexOf
来检查当前 id 是否在活动数组上并过滤数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.