如何解决需要帮助使用 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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。