Sanity GROQ query to get single item from an array based on slug or reference.
This GROQ query is used to get contents of an array item based on a filter, so that only needed items are fetched instead of full array.
By Surjith S M
groq.js
*[_type == "item" && slug.current == $slug][0] {
...,
content[product->slug.current == $productSlug][0]
}
// params
// {
// "slug": "main-slug",
// "productSlug": "slug-to-filter"
// }
data-structure
// data structure
{
title: "",
_id: "",
content: [
{
product: {
_ref: ""
},
body: {
...
}
},
{
product: {
_ref: ""
},
body: {
...
}
},
...
]
}result
// data
{
title: "",
_id: "",
// content[] array became a single object
content: {
product: {
_ref: ""
},
body: {
...
}
}
}From the following data structure, we need to get a single item from the content array based on product._ref. So we use the slug filter inside the array. This is the easiet method.
content[product->slug.current == $productSlug][0]
The above query says, only take items from the content array when product slug matches the $productSlug params and [0] says only display the first one so it become an object.
You can avoid [0] if you have multiple items or keep it as an array.
Contributor

Surjith S M
Web Designer & Front-end Developer. Figma, TailwindCSS & Next.js
India