需要帮助使用 javascript 为 Next.js 站点过滤 Contentful 上的帖子

Needs help filtering posts on Contentful using javascript for a Next.js site

我正在用 Contentful 为 Next.js 博客提供内容,并在首页查询一些 post。即使我可以 .filter() 通过使用一个简单的布尔值来展示 posts 我似乎无法理解如何获取 posts 以匹配我 post 中的类别结构。

这是我对特色 post 的查询的示例。

{posts.filter((posts) => (posts.fields.postDestaque)) // it filters posts that have 'postDestaque' false or null
   .slice(0, 6) // cuts off the excess 
   .map((post, i) => { // maps the posts and returns the component
   
   return <PostVertical key={i} post={post} noCats={noCats} noData={noData} />
})}

类别保存在一个数组中,该数组包含包含每个类别的名称和 slug 的字段对象,如下所示:

0:
  fields:
    categorias: Array(2)
      0:
        fields:
          nome: "Main Category"
          slug: "main-category"
      1:
        fields:
          nome: "Other Category"
          slug: "other-category"

我是一名前端人员,所以我不知道如何过滤类别的 post。我认为 .find() 可以工作,但它只会 return 与之匹配的对象,因此,类别本身。另外,我不明白如何获取第二个数组并测试 post 对象本身。我可以使用其他方法代替过滤或查找吗?

非常感谢对此的任何评论。

如果您要过滤的是一个数组,您可以只使用 .filter.some 我在下面添加了一小段代码,但您只想确保您 return 一个布尔值,一旦您找到要过滤的类别,.some 就会执行此操作。

posts.filter(post => post.fields.categorias.some(categoria => categoria.slug === 'main-category'));

const posts = [{
    fields: {
      categorias: [{
          noma: 'Main Category',
          slug: 'main-category',
        },

        {
          noma: 'Other Category',
          slug: 'other-category',
        },
      ],
    },
  },
  {
    fields: {
      categorias: [{
          noma: 'Main Category1',
          slug: 'main-category1',
        },

        {
          noma: 'Other Category1',
          slug: 'other-category1',
        },
      ],
    },
  },
  {
    fields: {
      categorias: [{
          noma: 'Main Category2',
          slug: 'main-category2',
        },

        {
          noma: 'Other Category2',
          slug: 'other-category2',
        },
      ],
    },

  },
];

const byCategory = category => post => post.fields.categorias.some(categoria => categoria.slug === category);
const byMainCategory = byCategory('main-category');
const filteredByCategorias = posts.filter(byMainCategory)

console.log("filtered by categorias", filteredByCategorias)