How to set keys for the return of a query in Sanity.io
7 replies
Last updated: Dec 8, 2022
O
Need help 🙏
Is there a way to set the key for the return of a query.
For example, this query
returns this:
Is there a way to set the key for the return of a query.
For example, this query
*[_type == 'navigation'] { navId { current }, "id": navId.current, items[] { link[0], hasSubNavigation == true => { subLinks }, hasSubNavigation, maxItems >= 0 => { 'maxItems': maxItems - 1 } } }
Dec 8, 2022, 6:37 PM
O
and I would like that instead of it returning
0and
1as keys it would return the
idas the key, bonus points if the id can be converted to camel case
Dec 8, 2022, 6:39 PM
O
or maybe even explicitly naming returns found by
all in the same query?
id, something like this:
mainNavigation: [_type == 'navigation' && navId.current == 'main-navigation'][0] footerNavigation: [_type == 'navigation' && navId.current == 'footer-navigation'][0]
Dec 8, 2022, 6:48 PM
O
the best I got so far is this:
but it still returns index as key for the object instead of just
*[_type == 'navigation'] { navId.current == 'main-navigation' => { "mainNav": { "id": navId.current, items[] { link[0], hasSubNavigation == true => { subLinks }, hasSubNavigation, maxItems >= 0 => { 'maxItems': maxItems - 1 } } } }, navId.current == 'footer-left' => { "leftFooter": { "id": navId.current, items[] { link[0], hasSubNavigation == true => { subLinks }, hasSubNavigation, maxItems >= 0 => { 'maxItems': maxItems - 1 } } } } }
mainNavand
leftFooter
Dec 8, 2022, 7:02 PM
Hmm, I think the problem here is that those numbers aren't actually in the data. They're just there to help distinguish the different items in the array. You could use a named field to set a 'key' on the objects (which it looks like you already got!).
Dec 8, 2022, 11:34 PM
O
yes, but I would like to know if there is a way to get and object instead of an array to be able to destructure each navigation. I kind of salved this issue using reduce like this:
but just wanted to be sure if returning and object with keys was an option using groq
const navigation = navigationArray?.reduce( (acc: any, navItem: SanityNavigation) => { return {...acc, ...navItem}; }, {}, );
Dec 8, 2022, 11:42 PM
I think you'll have to stick with the reduce method. A key has to be a hardcoded string value, so you wouldn't be able to pass in a value from the item in the array.
Dec 8, 2022, 11:45 PM
O
ok, all good! thanks.
Dec 8, 2022, 11:45 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.