I want to filter my data to dynamically. But our condition must be dynamic. I wanna call this method on the <select (change)="filterData($event.target.value,'jobStatusId')" >
However, jobStatusId
can be change. It can be jobTypeId
. How can I make it dynamic.
I try this, for example I have a data like this; `
filteredData= [
{
"jobStatusId": 1,
"jobTypeId": 2,
"jobPriorityId": 3,
},
{
"jobStatusId": 2,
"jobTypeId": 3,
"jobPriorityId": 3,
},
{
"jobStatusId": 2,
"jobTypeId": 3,
"jobPriorityId": 4,
}
]
Also I write a method like;
filterData(id, condition: string) {
this.filteredData = this.filteredData.filter(
(a) => a.condition === id
);
}
In this method, let's focus condition: string
. condition
can be jobStatusId
or jobTypeId
or jobPriorityId
. I wanna make it dynamic.
For example;
When I call like, filterData(2,jobStatusId)
my data should be:
{
"jobStatusId": 2,
"jobTypeId": 3,
"jobPriorityId": 3,
},
{
"jobStatusId": 2,
"jobTypeId": 3,
"jobPriorityId": 4,
}
If I call it twice like:
filterData(2,jobStatusId)
filterData(4,jobPriorityId)
Then, my filteredData should be:
{
"jobStatusId": 2,
"jobTypeId": 3,
"jobPriorityId": 4,
}
How can I make it dynamic? How can I make it like that? If you have better solution, you can tell me. However I wanna call this method on the <select (change)="filterData($event.target.value,'jobStatusId')" >
CodePudding user response:
I find a way using if-else but, I'm really curious about it. Is there any way to dynamically? My solution:
if (condition === "jobPriorityId") {
this.filteredData = this.filteredData.filter(
(a) => a.jobPriorityId=== id
);
}
if (condition === "jobStatusId ") {
this.filteredData = this.filteredData.filter(
(a) => a.jobStatusId === id
);
}
if (condition === "jobTypeId ") {
this.filteredData = this.filteredData.filter(
(a) => a.jobTypeId === id
);
}
CodePudding user response:
Create a type based of your javascript object like this:
// somewhere in your project
export type JobType = 'jobTypeId' | 'jobStatusId' | 'jobPriorityId';
Then, the condition is going to be of type JobType
filterData(id: number, condition: JobType): void {
const filtered = this.filteredData.filter(d => d[condition] === id);
return filtered;
}
In the template HTML, you need to send the exact value that matches any JobType
value, otherwise, Typescript
will complain:
<!-- works -->
<select (change)=filtered($event.target.value, 'jobStatusId') >
<!-- doesn't work -->
<select (change)=filtered($event.target.value, 'invalid-value') >