Mam listę konwencji poniżej, chcę filtrować tę listę według specjalizacji, tzn. jak wpisuję 15 to zwraca konwencje o id 1 i 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]
}
]
}
]
Próbowałem z tą funkcją, ale nic nie zwracam
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));
});
2
Aymen Kanzari
23 listopad 2018, 17:17
1 odpowiedź
Najlepsza odpowiedź
Array#some
jest naprawdę przydatne do takich rzeczy:
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(...)
wywoła swój predykat z każdym wpisem, dopóki się nie skończy (some
zwraca false
) lub predykat zwróci prawdziwą wartość (some
zwraca true
); to samo z activity.specialitiesId.some(...)
.
Przykład JavaScript na żywo:
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;
}
5
T.J. Crowder
23 listopad 2018, 17:26
Podobne pytania
Nowe pytania
angular
Pytania o Angular (nie mylić z AngularJS), frameworku sieciowym od Google. Użyj tego tagu w przypadku pytań dotyczących Angulara, które nie są specyficzne dla pojedynczej wersji. W przypadku starszej platformy internetowej AngularJS (1.x) użyj tagu angularjs.