我有一组服务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);
}
});
});
答案 0 :(得分:5)
您可以使用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)
答案 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是否在活动阵列上并过滤数组。