Extracting referenced images from an object array in Sanity.io

3 replies
Last updated: May 17, 2020
Hey, I have a reference array to an object with bits of information (called socials), mainly text, and then inside socials I have another reference to an image document. On the front end :`*[_type == "header"]{logo, invertedLogo, menu, socials}` any tips on how would I go about extract that referenced image from socials to the imgBuilder and extracting the rest of the information from socials at the same time?
AI Update

Based on your query structure, you need to dereference both the socials array and the nested image reference within each social object. Here's how to handle this in GROQ:

*[_type == "header"]{
  logo,
  invertedLogo,
  menu,
  socials[]{
    ...,
    image->
  }
}

The key is using the array projection syntax with the reference operator. The socials[] iterates through your reference array, ... spreads all the fields from each socials object (like text fields), and image-> dereferences the nested image reference.

If you want to be more explicit about which fields to return, you can do:

*[_type == "header"]{
  logo,
  invertedLogo,
  menu,
  socials[]{
    text,
    url,
    // other fields from socials
    image->{
      asset->{
        _id,
        url,
        metadata
      }
    }
  }
}

This gives you the image asset data ready for your image builder. On the frontend, you can then pass social.image.asset to your imgBuilder:

const imageUrl = imgBuilder.image(social.image.asset).url()

The -> operator internally executes a subquery to fetch the referenced document, so this works even with nested references. Just be aware that resolving multiple references can impact query performance if you have many socials with images, though for a header component this should be fine.

socials{image->asset._ref} or something like it πŸ™‚
Thank you, doing socials[]{...otherinfo, image[]->{image}} worked
it feels like I could do it in less steps but at least it works πŸ™‚

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?