Is there a way to get the key in an array when resolving the references?
Good news - there's a specific pattern to preserve the _key when dereferencing array items in GROQ!
When you use the -> operator to dereference, it replaces the reference object with the referenced document's content, which strips away the original _key. To keep it, you need to explicitly project the _key first, then spread the dereferenced content:
*[_type == "category"] {
events[]{
_key,
...(@->)
}
}The key here is using @-> instead of just ->. The @ refers to the current element in the array iteration, and then you spread the dereferenced content with ...(@->) after explicitly including _key.
This pattern works because:
_keyis explicitly projected first from the reference object@->dereferences the current array item- The spread operator
...merges the dereferenced document's fields - The result contains both the original
_keyand all fields from the referenced document
So your query would become:
*[_type == "category"] {
events[]{
_key,
...(@->{_id})
}
}Or if you want all fields from the referenced event:
*[_type == "category"] {
events[]{
_key,
...(@->)
}
}This is particularly useful when you need the _key for React list rendering (as the key prop) or tracking specific array items in your application. The _key documentation has more details on working with array keys in different contexts.
Show original thread6 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.