gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:00:08 25 4
gpt4 key购买 nike

我有一个包含服务 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com