簡體   English   中英

按值的子數組過濾對象數組

[英]Filter array of objects by sub array of values

這是我想要做的:

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']}]

問題是我不確定如何在給定另一個值數組的情況下過濾數組。 如果“過濾器”只是一個字符串,那么我可以這樣做:

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

但是如果過濾器是一個值數組,這顯然不起作用。

非常感謝任何幫助。

你很親近。 看起來您需要的是數組.some方法。 如果任何項目的回調為真,則該方法將返回真,因此您需要將“某些”類型包含在過濾器列表中:

 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))))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM