Query array of images for ALT and URL in GROQ
Please see image, from this data structure I would like to get from each item in array an ALT and URL to the image
🤔
Based on the information I found, here's how to query an array of images to get both the URL and alt text for each image using GROQ:
*[_type == 'yourDocumentType'] {
images[] {
'url': asset->url,
alt
}
}The key syntax here is images[] followed by a projection {} where you specify the fields you want. Here's what's happening:
images[]- This iterates through each item in your images arrayalt- This directly accesses the alt field on each image object
Important note: Don't use images[]-> (with the arrow after the brackets). The dereference operator -> should only be used when accessing the asset reference itself, not on the array.
If you have a more complex schema where you need to access other metadata, you can expand the projection:
*[_type == 'page'] {
title,
images[] {
'url': asset->url,
alt,
'width': asset->metadata.dimensions.width,
'height': asset->metadata.dimensions.height
}
}This pattern works because in Sanity, images are stored as references to asset documents, and GROQ's projection syntax lets you reshape the data from arrays into exactly the structure you need. You can use projections to select specific fields, rename them, and even follow references to build the exact JSON structure your application requires.
Show original thread7 replies
Was this answer helpful?
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.