How to get the image asset of each speaker in a Sanity.io array

5 replies
Last updated: Mar 17, 2021
Hi there! , I’m sorry but I couldn’t find this question anywhere but pretty sure has been answered / is on the docs because is a basic one.I’ve an array of ‘speakers’

{

title: "Speakers",

name: "speakers",

type: "array",

of: [

{

name: "speaker",

title: "Speaker",

type: "object",

fields: [

{

name: "name",

title: "Name",

type: "string",

},

{

name: "slug",

title: "Slug",

type: "slug",

options: {

source: "name",

maxLength: 96,

},

},

{

name: "image",

title: "Image",

type: "image",

options: {

hotspot: true,

},

},

{

name: "bio",

title: "Bio",

type: "array",

of: [

{

title: "Block",

type: "block",

styles: [{ title: "Normal", value: "normal" }],

lists: [],

},

],

},

],

preview: {

select: {

title: "name",

media: "image",

},

},

},

],

}
and I want to get the image asset of each one so I can iterate through the array and display it.
how would it be ?
Thank you in advance
Mar 17, 2021, 6:54 PM
Hi Milton. There are a few ways you could do this depending on what data you want returned. To get the image asset you’ll use the dereferencing operator (
->
). To get the rest of the data as well you’ll use
. You could also explicitly name each field if you wanted.
So, if you’re querying where
_type == "post"
you might do something like:

*[_type == "post"] {
  speakers[] {
    "image": image.asset->,
    ...
  },
  ...
}
That will:

1. Recurse through every document where
_type == "post"
.2. Recurse through the
speakers[]
array.3. Follow the reference to
image.asset
and put it into a property called
"image"
.4. Return the rest of the properties in
speakers[]
.5. Return the rest of the properties in each document (of type
post
).
Mar 17, 2021, 7:24 PM
If you only want the image details, you might do something like:

{"image": *[_type == "post"] | ([speakers[].image.asset->])}
Or just take out the ellipses (…) from the query above.
Mar 17, 2021, 7:28 PM
Works Like charm Geoff , thank you so much !the only thing I had to add was ‘url’ next to the arrow.


speakers[] {

"image": image.asset->url,

...

}

otherwise it wouldnt work
🤷‍♂️thanks again !
Mar 17, 2021, 7:31 PM
Glad to hear it! If you’re using this to display images on your front end, you can use the Sanity image-url builder and all you have to pass into it is your image (you don’t need to dereference or specify the url).
Mar 17, 2021, 7:33 PM
Great! thanks !
Mar 17, 2021, 7:36 PM

Sanity– build remarkable experiences at scale

Sanity is a modern 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?