javascript - 需要帮助使用 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 对象本身。我可以使用另一种方法来代替过滤器或查找吗?
非常感谢您对此的任何评论。
解决方案
如果它是您要过滤的数组,您可以不使用.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)
推荐阅读
- python - 如何更改 pandas groupby.agg 函数的输入参数?
- python - 连接多索引
- reactjs - undefined this.setState inside 'then' 块
- stripe-payments - 条带订阅现在和每月的第一天付款
- c# - 从 C#/.NET 向命令行可执行文件输入密码
- wpf - screenwings如何停止每一个截图?
- git - 在两个帐户之间将 TFVC 存储库迁移到 Git - 使用 git-tfs 克隆 TFVC 存储库的连接问题
- azure-logic-apps - 逻辑应用创建包含多行的 HTML 表
- javascript - 使用 onSnapshot 时如何避免使用嵌套的 try catch?
- database - 是否可以存储每行数据的历史配置设置,而无需将所有配置设置塞进每行数据?