Query array of images for ALT and URL in GROQ

7 replies
Last updated: Jan 12, 2022
SOLVEDHow with GROQ I can query an array of images url’s?
Please see image, from this data structure I would like to get from each item in array an ALT and URL to the image
πŸ€”
AI Update

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 array
  • asset->url - The -> operator dereferences the image asset reference to get the actual URL
  • alt - 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 thread
7 replies
HA! solved πŸ˜„
logotypes[].asset->url
Haha, beat me to it!
user M
πŸ˜„
haha, you both beat me to it. Was just typing a reply!
You can also use Sanity's Image url builder package if your project is in js/ts.
With that package you can transform the image, similar to cloudinary.
user M
,
user H
many thanks for your help πŸ™‚ Have a nice day πŸ™‚
You as well!

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?