[英]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.