How to set keys for the return of a query in Sanity.io

7 replies
Last updated: Dec 8, 2022
Need help πŸ™
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
      }
    }

  }
returns this:
Dec 8, 2022, 6:37 PM
and I would like that instead of it returning
0
and
1
as keys it would return the
id
as the key, bonus points if the id can be converted to camel case
Dec 8, 2022, 6:39 PM
or maybe even explicitly naming returns found by
id
, something like this:

mainNavigation: [_type == 'navigation' && navId.current == 'main-navigation'][0]
footerNavigation: [_type == 'navigation' && navId.current == 'footer-navigation'][0]
all in the same query?
Dec 8, 2022, 6:48 PM
the best I got so far is this:

*[_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
        }
      }
    }
  }
}
but it still returns index as key for the object instead of just
mainNav
and
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
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:

const navigation = navigationArray?.reduce(
  (acc: any, navItem: SanityNavigation) => {
    return {...acc, ...navItem};
  },
  {},
);
but just wanted to be sure if returning and object with keys was an option using groq
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
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.

Was this answer helpful?