简体   繁体   English

基于另一个数组过滤数组

[英]Filtering array based on another array

I am trying to filter arr1, with respect to arr2 what I am trying to achieve is, get all objects of arr1 where it's corresponding "genre" property in arr2 is "true"我正在尝试过滤 arr1,关于 arr2 我想要实现的是,获取 arr1 的所有对象,其中它在 arr2 中对应的“流派”属性为“真”

const arr1=[
  {
    "id":1,"genre":["horror","drama","mystery"]
  },
   {
    "id":2,"genre":["romance"]
  },
   {
    "id":3,"genre":["adventure","drama"]
  },
]

const arr2=[
  {
    "genre":"horror",
    "checked":false
  },
  {
    "genre":"drama",
    "checked":true
  },
  {
    "genre":"mystery",
    "checked":false
  },
  {
    "genre":"romance",
    "checked":false
  },
  {
    "genre":"adventure",
    "checked":true
  }
]

so the desired output would be:所以所需的输出将是:

[
 {
   "id":1,"genre":["horror","drama","mystery"]
  },
{
    "id":3,"genre":["adventure","drama"]
  },
]

I have tried some configurations the javascript filter methods but i just can't think of something that works as described.我已经尝试了一些配置 javascript 过滤器方法,但我只是想不出像描述的那样工作的东西。 Any help would be appreciated.任何帮助,将不胜感激。 Thank you.谢谢你。

This should work.这应该工作。

Use .filter on first array and .some on the other array to determine if it is checked and element of first array contains target genre using .indexOf or even better .includes在第一个数组上使用.filter并在另一个数组上使用.some来确定它是否被checked并且第一个数组的元素包含使用.indexOf或更好.includes的目标genre

 const arr1=[ { "id":1,"genre":["horror","drama","mystery"] }, { "id":2,"genre":["romance"] }, { "id":3,"genre":["adventure","drama"] }, ] const arr2=[ { "genre":"horror", "checked":false }, { "genre":"drama", "checked":true }, { "genre":"mystery", "checked":false }, { "genre":"romance", "checked":false }, { "genre":"adventure", "checked":true } ] const result = arr1.filter(a1 => arr2.some(a2 => a2.checked && a1.genre.includes(a2.genre))) console.log(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 基于另一个数组对数组进行排序/过滤 - Sorting/Filtering on array based on another array 根据另一个布尔数组过滤数组 - Filtering an Array based on another Boolean array 基于另一个数组过滤对象数组返回新数组javascript - filtering an array of objects based on another array returning new array javascript 基于另一个数组元素过滤多维数组 - Filtering multi-dimensional array based on another array elements Angular 基于另一个数组的嵌套数组过滤(导航菜单) - Angular nested array filtering based on another array (Navigation menu) 根据 Google Apps 脚本中的另一个数组过滤数组 - Filtering an array based on another Array in Google Apps Script 根据包含 javascript 中的键的另一个数组过滤对象数组 - filtering an array of objects based on another array containing keys in javascript Typescript 基于另一个数组对嵌套数组进行数据过滤 - Typescript data filtering on nested array based on another array 基于javascript中具有多个数组的另一个对象的过滤来过滤数组 - Filter Array based on the Filtering of Another Object having Multiple array in javascript 根据另一个值数组过滤对象数组,返回一个空列表 - filtering an array of objects based on another array of values, returning an empty list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM