我有下面的约定列表,我想按专业过滤此列表,即当我输入 15 时,它返回 id 1 和 2 的约定
[
{
"id": 1,
"typeActivities": [
{
"id"=11,
"specialitiesId": [10, 15]
}
]
},
{
"id": 2,
"typeActivities": [
{
"id"=22,
"specialitiesId": [10]
},
{
"id"=222,
"specialitiesId": [15]
}
]
},
{
"id": 3,
"typeActivities": [
{
"id"=33,
"specialitiesId": [12]
}
]
}
]
我尝试过这个函数,但没有返回任何内容
let input: number = 15;
let convention: Convention[];
convention = this.conventions.filter(convention => {
let typeActivities: TypeActivity[] = convention.typeActivities.filter(typeActivitiy => {
if (typeActivitiy.specialitiesId) {
return input == typeActivitiy.specialitiesId.find(id => id == input);
}
});
//console.log(convention.typeActivities.map(i => i.id).filter(item => typeActivities.map(i => i.id).indexOf(item) >= 0));
});
最佳答案
Array#some
对于这样的事情确实很有用:
let input: number = 15;
let convention: Convention[];
convention = this.conventions.filter(convention =>
convention.typeActivities.some(activity =>
activity.specialitiesId.some(e => e == input)
)
);
convention.typeActivities.some(...)
将对每个条目调用其谓词,直到它用完(some
返回 false
)或者谓词返回真值(some
返回 true
);与 activity.specialitiesId.some(...)
相同。
实时 JavaScript 示例:
const example = {
conventions: [
{
"id": 1,
"typeActivities": [
{
"id": 11,
"specialitiesId": [10, 15]
}
]
},
{
"id": 2,
"typeActivities": [
{
"id": 22,
"specialitiesId": [10]
},
{
"id": 222,
"specialitiesId": [15]
}
]
},
{
"id": 3,
"typeActivities": [
{
"id": 33,
"specialitiesId": [12]
}
]
}
],
find(input) {
let convention;
convention = this.conventions.filter(convention =>
convention.typeActivities.some(activity =>
activity.specialitiesId.some(e => e == input)
)
);
return convention;
}
};
console.log(example.find(15));
.as-console-wrapper {
max-height: 100% !important;
}
关于angular - Typescript 使用 filter() 过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53448333/