I'm having a bit of trouble. This is the data that I'm receiving back from my headless CMS (Sanity) and I want to be able to create a filter that matches the selected category. I know that if my response was a category object that I could easily do the filter like so. However, I have some blogs that fall into several categories. I'm assuming that I would need to map through the category array and apply the filter here. Any help would be appreciated. Thank you!
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"
}
}
]
},
CodePudding user response:
The some()
function returns true if at least one of the array items match the condition. Your blog filter will be something like this:
blogs.filter((blog) =>
blog.category?.some((category) => category?.slug?.current === activeCategory)
)