GROQ: Resolve array references while keeping _key property
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
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.