Is there a way to get the key in an array when resolving the references?

6 replies
Last updated: Sep 10, 2020
Is there a way to get the key in an array when resolving the references?
*[_type == "category"] {
events[]-> {_key, _id}
}
I cant find a way to include the
_key
here.
AI Update

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:

  1. _key is explicitly projected first from the reference object
  2. @-> dereferences the current array item
  3. The spread operator ... merges the dereferenced document's fields
  4. The result contains both the original _key and 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 thread
6 replies
Could you post an example of a category document? Easier to help when seeing the document structure
{
  "events": [
    {
      "_key": "f9d29ec438bf",
      "_ref": "5b94ed5c-064d-4fe8-bafe-e53920984f65",
      "_type": "reference"
    }
  ]
}
events[]{
 _key, 
  @->
}
Perhaps?
Getting close 🙂 I needed to put it in an object.
*[_type == "category"][0] {
events[] {
  _key,
  "something": @-> {...}
}
}
Any ideas how to make attach it to the parent?
  events[]{
    _key,
    ...@->
  }
Nice! Thanks ❤️

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.

Was this answer helpful?