GROQ: Resolve array references while keeping _key property
This query: *[_id == $id]{items}
Gives me this result:
[
{
"items": [
{
"_key": "1acc50cf5ffc",
"_ref": "f4cae0ea-16a0-446b-a835-a93b001dd1eb",
"_type": "reference"
},
{
"_key": "be9bad61ab5e",
"_ref": "098b7fce-f26c-4643-90c1-8ef6b8f61bbf",
"_type": "reference"
}
]
}
][]->to items resolves each item reference, but it also strips out the
_keyproperty. Is there a way to include it while still resolving the reference all with a single GROQ query?
Perfect! I found exactly what you need. When you use the -> operator to dereference, it strips out the _key property, but there's a clean way to preserve it.
You can explicitly include the _key in your projection while spreading the dereferenced content:
*[_id == $id]{
items[]{
_key,
...(@->)
}
}This pattern works by:
items[]- iterates over each item in the array_key- explicitly includes the key property...(@->)- spreads all properties from the dereferenced document (the@refers to the current item being iterated)
So if your referenced documents have properties like title and description, your result would look like:
[
{
"items": [
{
"_key": "1acc50cf5ffc",
"title": "First Item",
"description": "..."
},
{
"_key": "be9bad61ab5e",
"title": "Second Item",
"description": "..."
}
]
}
]This is the recommended approach for preserving _key during dereferencing, and it's especially useful when you need those keys as React key props when rendering lists!
Show original thread8 replies
Was this answer helpful?
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.