How to remove null values for undefined keys in GROQ arrays.
21 replies
Last updated: Nov 14, 2022
K
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
I tried
companiesdoesn’t exist?
{ ..., content[]{ ..., companies[]{ ..., company-> } }
defined()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
C
Have you tried to filter it? Maybe something like
{ ..., content[defined(companies)]{ ..., companies[]{ ..., company-> } }
Nov 14, 2022, 1:48 PM
K
I want all items in
I don’t want those that haven’t got companies to have
content.Some items have
companieskey, with companies in. But some doesn’t.
I don’t want those that haven’t got companies to have
companies:null.
Nov 14, 2022, 1:51 PM
C
so you basically just want the key removed?
Nov 14, 2022, 1:51 PM
C
in those cases
Nov 14, 2022, 1:51 PM
K
The key should only be there if it is defined.
Nov 14, 2022, 1:52 PM
C
maybe you could do a select then,
{ ..., content[] { ..., companies[] { ..., ...select( defined(company) => { "company": company-> })
Nov 14, 2022, 1:54 PM
K
Wouldn’t that still result in
companies:null?
Nov 14, 2022, 1:55 PM
C
yea you should move the select to companies instead of company, i just read it wrong
Nov 14, 2022, 1:56 PM
K
Ah great.. Thank you very much Casper. 💪
Nov 14, 2022, 1:56 PM
C
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
K
C
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
K
Yea it’s just my OCD that don’t want keys that aren’t supposed to be there… 🙈
Nov 14, 2022, 2:05 PM
K
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
C
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
C
Nov 14, 2022, 2:10 PM
K
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
C
=> is a conditional
Nov 14, 2022, 2:12 PM
K
Ah okay, so because defined returns a boolean, then the following projection is executed?
Nov 14, 2022, 2:13 PM
C
yea, basically what
...select()does but a bit easier
Nov 14, 2022, 2:14 PM
K
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.