🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

How to remove null values for undefined keys in GROQ arrays.

21 replies
Last updated: Nov 14, 2022
In GROQ, when resolving arrays, how do I only get the key if it exists, to prevent companies:null on array items where the key
doesn’t exist?
{ ..., content[]{ ..., companies[]{ ..., company-> } }
I tried
but I can’t seem to figure out the correct usage, or maybe that doesn’t even work here?
Nov 14, 2022, 1:15 PM
Have you tried to filter it? Maybe something like
{ ..., content[defined(companies)]{ ..., companies[]{ ..., company-> } }

Nov 14, 2022, 1:48 PM
I want all items in
.Some items have
key, with companies in. But some doesn’t.
I don’t want those that haven’t got companies to have
Nov 14, 2022, 1:51 PM
so you basically just want the key removed?
Nov 14, 2022, 1:51 PM
in those cases
Nov 14, 2022, 1:51 PM
The key should only be there if it is defined.
Nov 14, 2022, 1:52 PM
maybe you could do a select then,
{ ..., content[] { ..., companies[] { ..., ...select( defined(company) => { "company": company-> })
Nov 14, 2022, 1:54 PM
Wouldn’t that still result in
Nov 14, 2022, 1:55 PM
yea you should move the select to companies instead of company, i just read it wrong
Nov 14, 2022, 1:56 PM
Ah great.. Thank you very much Casper. 💪
Nov 14, 2022, 1:56 PM
btw not sure about performance etc, maybe it is a heavier query to do, usually groq questions are resolved quite quickly in groq
Nov 14, 2022, 1:57 PM
It doesn’t matter in my case, as I am just building a static website from it on build time.I actually posted a question in
groq first, but ther were no reply so I deleted it and posted it in help. 😄
Nov 14, 2022, 1:59 PM
are you building in js? curious why you need the null values removed, since undefined vs null can be handled nearly the same. complexity of the query increases a bit
Nov 14, 2022, 2:04 PM
Yea it’s just my OCD that don’t want keys that aren’t supposed to be there… 🙈
Nov 14, 2022, 2:05 PM
And want to learn GROQ in detail, so I just thought about how that would be possible, and couldn’t get it to work.
Nov 14, 2022, 2:06 PM
could be a more elegant way than select though... reading through the docs you can probably do an inline condition:
{ ..., content[] {
  defined(companies) => { /* and so on */ }
Nov 14, 2022, 2:09 PM
I never saw
for projection, only
.So that’s because it’s a different set? That means I could have another query if it was not defined, right?
Nov 14, 2022, 2:12 PM
=> is a conditional
Nov 14, 2022, 2:12 PM
Ah okay, so because defined returns a boolean, then the following projection is executed?
Nov 14, 2022, 2:13 PM
yea, basically what
does but a bit easier
Nov 14, 2022, 2:14 PM
Great. Thanks a lot Casper. 💪
Nov 14, 2022, 2:14 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?