简体   繁体   中英

Typescript Filter Array of Objects with an Array of Strings by Multiple Keywords

I understand how to filter a single attribute in an array of an objects with just one keyword. I currently have a filter service that filters out an array of objects by a single attribute using a single keyword, but I cannot figure out how to do it with multiple keywords on an array of objects. This is what I have so far:

I have an interface Restaurant which is what the Array of objects is:

export interface Restaurant {
id: number;
name: string;
tags: string[];
}

Right now what I have filters by the name attribute, what I want to do is filter the restaurants by the array of tags attribute with an array of preferences in the service class.

@Injectable()
export class PreferencesFilterService {


getFilteredRestaurants(list: Restaurant[]): Restaurant[] {
    return list.filter(function(restaurant){
        restaurant.name === "Mexican";
    });
}
}

and I would need it to perform like this pseudocode:

@Injectable()
export class PreferencesFilterService {

preferencesList: string[];


getFilteredRestaurants(list: Restaurant[]): Restaurant[] {
    return list.filter(function(restaurant){

      //loop through each restaurants "tags" attribute
      //return an array of restaurants that pass the following test:
      //  --> The restaurant's tags array strings match with at least 1 
      //      of the strings in the preferencesList array


    });
} 
}

I am very new to javascript, Typescript, and web development as a whole so any help or pointers in the right direction would be greatly appreciated. Thank you very much for your time.

EDIT:
I think that my question was unclear, in the inner loop I need to loop through and check each value in the preferences list, but I do not want to compare it to the "restaurant.name" attribute, I want to compare it to all of the values in the "tags" array attribute. Sorry for the miscommunication.

You can do it like this

@Injectable()
export class PreferencesFilterService {

    var preferencesList: string[] = ['Mexico', 'Brazil'];

    getFilteredRestaurants(list: Restaurant[]): Restaurant[] {
        return list.filter(function(restaurant) {
            for (let tag in restaurant){
                if (preferencesList.indexOf(restaurant[tag])!=-1){
                    return true;
                }
            }
            return false;
        });
    }
}

I put Mexico and Brazil in the preferences list, you can add as many as you want.

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM