Using coalesce in projection and filtering out null results
You can conditionally include fields in GROQ projections using conditional object attributes! There are a few ways to handle this:
Option 1: Conditional attribute syntax
The cleanest approach is to use a condition before the field definition:
{
defined(coalesce(strapLine, strapline)) => {
"strapline": coalesce(strapLine, strapline)
}
}This will only include the strapline field in your results when at least one of the source fields has a value. The defined() function checks if a value exists and is not null, which pairs perfectly with coalesce().
Option 2: Using select() function
You can also use the select() function, which works like a switch statement:
{
"strapline": select(
defined(strapLine) => strapLine,
defined(strapline) => strapline
)
}With select(), if neither condition matches, the field won't be included in the result at all (or will be null).
Option 3: Shorter conditional syntax
If you want a more compact version:
{
coalesce(strapLine, strapline) != null => "strapline": coalesce(strapLine, strapline)
}All three approaches will prevent the field from appearing in your results when both strapLine and strapline are null or undefined. The first option with defined() is generally the most readable and is the recommended pattern for this use case.
Show original thread2 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.