GROQ: Prevent null values when resolving optional array keys
Perfect! You're on the right track with defined(). The solution is to use conditional projection to only include the companies key when it exists. Here's how to do it:
{
...,
content[]{
...,
defined(companies) => {
"companies": companies[]{
...,
company->
}
}
}
}The key is wrapping the field in a conditional projection using the => operator. When companies is defined, it includes the companies key with its resolved array. When it's not defined, the entire key is omitted from the result (rather than appearing as companies: null).
As mentioned in the defined() function documentation, when using the API, you need to wrap the return value in curly braces with the key name explicitly stated as a string.
If you have multiple conditional fields at the same level, you can chain them:
{
...,
content[]{
...,
defined(companies) => {
"companies": companies[]{..., company->}
},
defined(otherField) => {otherField}
}
}This pattern works because defined() returns true when the property exists and is not null, and the conditional projection operator => only includes the result when the condition is true.
Show original thread21 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.