首页 > 解决方案 > 需要帮助使用 javascript 为 Next.js 网站过滤 Contentful 上的帖子

问题描述

我正在为 Next.js 博客提供 Contentful 并在首页查询一些帖子。即使我可以.filter()使用简单的布尔值来推荐帖子,我似乎也无法理解如何在帖子结构中获取匹配类别的帖子。

这是我对精选帖子的查询的示例。

{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"

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

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

标签: javascriptreactjsnext.jscontentful

解决方案


如果它是您要过滤的数组,您可以不使用.filter并且.some我在下面添加了小片段,但是您只想确保在找到要过滤的类别后返回一个布尔值,.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)


推荐阅读