用另一个数组筛选复杂数组


let array1 = [
{
id: 1,
genres: [
{ id: 4, title: "qqqq" },
{ id: 9, title: "zzzz" },
{ id: 8, title: "eeee" },
],
},
{
id: 2,
genres: [
{ id: 2, title: "qwert" },
{ id: 4, title: "asdf" },
{ id: 5, title: "zxxcc" },
],
},
];
let array2 = [6, 8];

如果类型id存在于array2中,我需要过滤array1。所以在输出中,我应该只有array1的第一个元素。

如何做到这一点?

您可以使用filtersomeincludes:的组合

let array1 = [{id:1,genres:[{id:4,title:"qqqq" },{id:9,title:"zzzz"},{id:8,title:"eeee" }]},
{id:2,genres:[{id:2,title:"qwert"},{id:4,title:"asdf"},{id:5,title:"zxxcc"}]}];
let array2 = [6, 8];
let result = array1.filter(({genres}) => genres.some(({id}) => array2.includes(id)));
console.log(result);

使用filter函数。

一种方法:

let result = array1.filter(el => {
let output = false;
el.genres.forEach( genre => {
if (array2.includes(genre.id))
output = true;
});
return output;
});

最新更新