gpt4 book ai didi

angular - Typescript 使用 filter() 过滤数组

转载 作者:搜寻专家 更新时间:2023-10-30 21:18:59 27 4
gpt4 key购买 nike

我有下面的约定列表,我想按专业过滤此列表,即当我输入 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/

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