简体   繁体   中英

Filter array of objects by sub array of values

Here is what I am trying to do:

movies = [{'title': 'a', 'genres': ['Romance', 'Comedy']}, 
          {'title': 'b', 'genres': ['Drama', 'Comedy']}, 
          {'title': 'c', 'genres': ['Action', 'Adventure']}]

filters = ['Romance', 'Drama']

Desired contents of filtered array:

[{'title': 'a', 'genres': ['Romance', 'Comedy']}, 
 {'title': 'b', 'genres': ['Drama', 'Comedy']}]

The issue is that I am not sure how to filter an array given another array of values. If 'filters' was just a single string, then I could just do:

movies.filter(x => x.genres.includes(filters))

But this obviously won't work if filters is an array of values.

Any help is much appreciated.

You're very close. It looks like what you need is the array .some method. That method will return true if it's callback is true for any item, so what you need is for "some" genre to be included in the filter list:

 movies = [{ 'title': 'a', 'genres': ['Romance', 'Comedy'] }, { 'title': 'b', 'genres': ['Drama', 'Comedy'] }, { 'title': 'c', 'genres': ['Action', 'Adventure'] } ] filters = ['Romance', 'Drama'] //[{'title': 'a', 'genres': ['Romance', 'Comedy']}, // {'title': 'b', 'genres': ['Drama', 'Comedy']}] console.log(movies.filter(x => x.genres.some(g => filters.includes(g))))

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