Pass property of a class as a parameter to a function the can evaluate the property

Viewed 43

Assume I have a class defined as follow:

export class test {
    name: string,
    description: string,
    location: string,
    comment: string
}

let data: test[] = [];
data.push({'name': 'A', 'description':'Description A', 'location': 'Location 1', 'comment': 'Comment A'});
data.push({'name': 'B', 'description':'Description B', 'location': 'Location 1', 'comment': 'Comment B'});
data.push({'name': 'C', 'description':'Description C', 'location': 'Location 2', 'comment': 'Comment C'});

let result = this.search('location', 'Location 1'); // location, is the class attribute here

function search(attribute: string, value: string) {
    let response = data.filter(a => a.attribute.includes(value); 
    // the attribute in a.attribute has to translate to location so the line would read as
    // data.filter(a => a.location.includes(value);
    return response;
}

Is this possible in typescript? The outcome of the query would be the 1st two rows of the data array.

1 Answers

Sure, but you could also extend your search function slightly and make it generic, so you can include a data type in it, like so:

interface Test {
    name: string;
    description: string;
    location: string;
    comment: string;
}

function Search<T, K extends keyof T>(values: T[], attribute: K, searchValue: string): T[] {
    return values.filter(value => String(value[attribute]).includes(searchValue));
}

let data: Test[] = [];
data.push({'name': 'A', 'description':'Description A', 'location': 'Location 1', 'comment': 'Comment A'});
data.push({'name': 'B', 'description':'Description B', 'location': 'Location 1', 'comment': 'Comment B'});
data.push({'name': 'C', 'description':'Description C', 'location': 'Location 2', 'comment': 'Comment C'});

console.log(Search(data, 'location', 'Location 1'));
Related