Is there an easy way to get the reference data in a deeply nested component? I have a list of different components, some of them have arrays of references which I’d liketo...
Based on your question, you're dealing with a common GROQ challenge: dereferencing references in arrays while preserving the original structure for non-reference items. The issue with your current query body[]{ links[]-> } is that it's trying to project only the links field, which removes all other fields from components that don't have links.
The solution is to use the spread operator (...) to preserve the original content, then selectively override specific fields. Here's the pattern:
body[] {
...,
links[]->
}The ... spread operator includes all original fields from each component, and then links[]-> overrides just the links array with the dereferenced versions.
For more complex scenarios where you might have mixed content (some references, some inline objects), you can use the coalesce function to handle both cases gracefully:
body[] {
...,
links[] {
...,
"resolved": coalesce(@->, @)
}
}This pattern:
...preserves all original component fieldslinks[]iterates through the links array@->attempts to dereference if it's a reference@falls back to the original object if it's not a reference- The result is stored in a
resolvedfield
If you only need specific fields from the referenced documents, you can project them:
body[] {
...,
links[]-> {
_id,
title,
slug
}
}The key takeaway: always start with ... when you want to preserve the original structure, then add your reference dereferencing. This ensures components without the links field remain intact instead of being replaced with empty objects.
You can learn more about the reference access operator and projections in the GROQ joins documentation.
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.