按值的子数组过滤对象数组

问题描述:

这就是我要尝试的事情:

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

过滤数组的所需内容:

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

问题是我不确定在给定另一个值数组的情况下如何过滤数组。如果'filters'只是一个字符串,那么我可以这样做:

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.

任何帮助都很感激。

您非常关。看来您需要的是数组 .some 方法。如果该方法的回调对任何项目都为true,则该方法将返回true,因此您需要的是将某些流派包含在过滤器列表中:

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