You can always use another Object Member Access Pattern here.
Keeping d[keyToFilterOn] with the value of keyToFilterOn as 'role' is similar to doing d.role.
So why not doing something like this:
let keyToFilterOn = 'role'; // or id
const temp = this.temp.filter(d => {
return d[keyToFilterOn].toLowerCase().indexOf(val) !== -1 || !val;
});
This way, you won't have to create a function for it.
Alternative
You can create an AngularPipe and then use it in your TypeScript Class:
Here's the filter
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(temp: any[], filterBy: string, filterValue: any): any {
if (!filterBy || !filterValue) {
return input;
}
return temp.filter(d => {
return d[filterBy].toLowerCase().indexOf(filterValue) !== -1 || !filterValue;
});
}
}
Here's how to use it:
import { FilterPipe } from 'path/to/the/pipe';
class YourComponent {
YourFunction(value) {
let filteredData = new FilterPipe().transform(this.temp, keyToFilterOn, val);
}
}
Although Angular doesn't really recommend using a Pipe for filtering data. But since this is being used inside a class and not in the template, it's fine.
.filter()seems like a really questionable idea.closures. They are basically functions that can return functions with different parameters.