[英]Trouble filtering an array of objects based on a nested array
我有一组看起来像这样的对象:
const nodes = [{
post: 'a',
categories: [{title:'Events'}, {title: 'Announcements'}]
},
{
post: 'b',
categories: [ {title:'Events'}]
},
{
post: 'c',
categories: [ {title:'Announcements'}]
},
]
我需要像这样根据 arrays 过滤它们:
const sectionCategory1 = ['Events', 'Announcements']
const sectionCategory2 = ['Events']
这样只有包含 sectionCategory 条目的帖子才会保留。 例如,如果我使用 sectionCategory2 过滤器返回帖子 a 和 b。
我尝试了以下方法:
const categoryNodes = nodes.filter((node => sectionCategory2.includes( node.categories.map(n => n.title))))
和
const categoryNodes = nodes.filter((node => sectionCategory2.includes( node.categories)))
也没有用。 我敢肯定,我在这里缺少一些基本的东西,而且我知道以前也有人问过类似的问题,但是我已经尝试了其他解决方案,并且一直在反对这一点。
在特定节点的迭代中,您有 2 个 arrays 可以相互检查:要包含的类别,例如['Events']
,以及节点的类别标题,例如['Events', 'Announcements']
。 因此,您将需要一个嵌套循环,而不仅仅是一个.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.