简体   繁体   English

基于嵌套数组过滤对象数组时遇到问题

[英]Trouble filtering an array of objects based on a nested array

I've got an array of objects that looks like this:我有一组看起来像这样的对象:

const nodes = [{
     post: 'a',
     categories: [{title:'Events'}, {title: 'Announcements'}]
     },
     {
     post: 'b',
     categories: [ {title:'Events'}]
     },
     {
     post: 'c',
     categories: [ {title:'Announcements'}]
     },
]

and I need to filter them based on arrays like this:我需要像这样根据 arrays 过滤它们:

const sectionCategory1 = ['Events', 'Announcements']
const sectionCategory2 = ['Events']

so that only the posts that include the sectionCategory entries will remain.这样只有包含 sectionCategory 条目的帖子才会保留。 For instance if I use sectionCategory2 the filter returns posts a and b.例如,如果我使用 sectionCategory2 过滤器返回帖子 a 和 b。

I've tried the following:我尝试了以下方法:

const categoryNodes = nodes.filter((node => sectionCategory2.includes( node.categories.map(n => n.title))))

and

const categoryNodes = nodes.filter((node => sectionCategory2.includes( node.categories)))

didn't work either.也没有用。 I'm sure there's something fundamental that I'm missing here and I know similar questions have been asked before but I've tried the other solutions and just keep beating my head against this.我敢肯定,我在这里缺少一些基本的东西,而且我知道以前也有人问过类似的问题,但是我已经尝试了其他解决方案,并且一直在反对这一点。

Inside the iteration of a particular node, you have 2 arrays to check against each other: the categories to include, eg ['Events'] , and the category titles of the node, eg ['Events', 'Announcements'] .在特定节点的迭代中,您有 2 个 arrays 可以相互检查:要包含的类别,例如['Events'] ,以及节点的类别标题,例如['Events', 'Announcements'] So, you'll need a nested loop, not just a single .includes : iterate over every element of one array to see if any matches an element in the other array.因此,您将需要一个嵌套循环,而不仅仅是一个.includes :遍历一个数组的每个元素以查看是否有任何匹配另一个数组中的元素。

 const nodes = [{ post: 'a', categories: [{title:'Events'}, {title: 'Announcements'}] }, { post: 'b', categories: [ {title:'Events'}] }, { post: 'c', categories: [ {title:'Announcements'}] }, ] const sectionCategory2 = ['Events'] const categoryNodes = nodes.filter( node => node.categories.map(n => n.title).some(title => sectionCategory2.includes(title) ) ); console.log(categoryNodes);

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM