Querying and dereferencing specific objects in a Slack thread.

7 replies
Last updated: Oct 5, 2022
Hi guys, I have a query like this
*[current match "settings-*"]
that returns data to this effect:
        created_at: "", 
        id: "",
        current: "settings-head",
        menu: {
            _ref: "gc9fb2f4-3f4-4613-8332-52d0d312b6f8", 
            _type: "reference"
        created_at: "",
        current: "settings-footer"
        favicon: "something"
        created_at: "", 
        id: "", 
        current: "settings-current"
        instagram: "something"
In other words, the inner objects have some shared key-value pairs but mostly they are different. Now I need to dereference the
item in one of these inner objects. The only thing that has worked so far has been `*[current match "settings-*"] {..., menu->}`but that's far from ideal because it adds a
menu: null
to each of the objects that didn't contain the menu key initially (plus I don't know what would happen if any of them had the
item that wasn't a reference). Is there any way to target only the one menu item? For example to say, if the menu item is not null and is a reference, dereference it? Thank you!
Oct 5, 2022, 6:53 AM
user U
! You can use conditionals to control what's returned in these cases. Specifically, there's an example of conditionally expanding references here and a more broad example here .
Oct 5, 2022, 4:24 PM
Thanks but I've already tried so many different combinations of this and I can't get it to work 😭...
Oct 5, 2022, 6:19 PM
Could you please maybe nudge me a little more?
Oct 5, 2022, 6:19 PM
What have you tried? Can you share your code?
Oct 5, 2022, 6:21 PM
I'm sorry, I won't be of any help, probably can't share it, that's why I made up that snippet, it has the same structure... I don't have the history of what I've tried either.. Nevermind then
Oct 5, 2022, 6:34 PM
I got it right after so much time wasted on it yesterday! You've probably inspired me :)
    const query = `*[current match "settings-*"]{ ..., menu {
      _type == 'reference' => @->,
      _type != 'reference' => @,
    } }`
Oct 5, 2022, 6:51 PM
Awesome! So glad you got it! 💪
Oct 5, 2022, 6:56 PM

Sanity– build remarkable experiences at scale

The Sanity Composable Content Cloud is the 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?

Categorized in