无法根据嵌套数组过滤对象数组

洛根

我有一个看起来像这样的对象数组:

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

而且我需要根据这样的数组过滤它们:

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个数组要相互检查:要包含的类别(例如['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);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章