按值的子数组过滤对象数组 [英] Filter array of objects by sub array of values

查看:52
本文介绍了按值的子数组过滤对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我要尝试的事情:

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

这篇关于按值的子数组过滤对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆