Extracting referenced images from an object array in Sanity.io
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.
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.