如何在Sanity返回的嵌套对象数组中筛选多分类博客?
多分类博客筛选逻辑调整方案
问题说明
从Sanity无头CMS获取的博客数据中,category字段为数组结构(单篇博客可归属多个分类),原筛选代码仅适配单个分类对象的场景,需调整逻辑实现选中分类的筛选功能。
原筛选代码
const router = useRouter(); const { category: activeCategory } = router.query; const filteredBlogs = React.useMemo(() => { return activeCategory ? blogs.filter( (blog) => blog.category?.slug?.current === activeCategory ) : downloads; }, [activeCategory, blogs]);
示例数据
{ "mainImage": { "asset": { "url": "https://cdn.sanity.io/images/s4nay89j/production/186a158c78e3d37ebe43c4197fe5f8c7854d0ae1-750x500.webp" } }, "image": null, "title": "Keeping A Fitness Journal to Find Your Perfect Routine", "slug": { "current": "keeping-a-fitness-journal-to-find-your-perfect-routine" }, "date": "2022-06-12", "category": [ { "name": "Fitness", "slug": { "current": "fitness" } }, { "name": "Motivation", "slug": { "current": "motivation" } } ] }
修改后的代码
const router = useRouter(); const { category: activeCategory } = router.query; const filteredBlogs = React.useMemo(() => { if (!activeCategory) return blogs; return blogs.filter((blog) => { if (!blog.category) return false; // 遍历分类数组,匹配选中的分类slug return blog.category.some(cat => cat.slug?.current === activeCategory); }); }, [activeCategory, blogs]);
核心调整
- 替换匹配逻辑:用数组的
some()方法遍历分类数组,只要存在一个分类的slug.current与选中分类一致,就保留该博客,适配多分类场景。 - 增加空值防护:先判断
blog.category是否存在,避免调用数组方法时出现报错。 - 修正笔误:原代码默认返回
downloads,应为blogs,已修正。
内容的提问来源于stack exchange,提问作者a-quach
相关产品推荐
相关产品推荐

