Skip to main content
Solved

How do i use the last object in an array eg. item.product.images?


Forum|alt.badge.img+3

How would I go about using the last item in an array eg. item.product.images

 

To get the first image I’m using:

{{item.product.images.0.src}}

 

I’ve tried {{item.product.images.last.src}} without success.

Or is there any way to get the number of items in an array and save this as a variable

Eg. {% assign array_length = item.product.images | length %}

 

And then use this in the object call

 

{{item.product.images[array_length].src}}

Best answer by elisegaines

Hey @TheSuburbs! I’d recommend this code: 
 

{% for image in item.product.images %}{% if forloop.last %}{{ image.src }}{% endif %}{% endfor %}

 

It will run through all the images until it gets to the last one, then grab the source URL for that last image. Hope this helps! 

Elise

View original
Did this topic or the replies in the thread help you find an answer to your question?

3 replies

Forum|alt.badge.img+25
  • Customer Ed.
  • 86 replies
  • Answer
  • June 3, 2021

Hey @TheSuburbs! I’d recommend this code: 
 

{% for image in item.product.images %}{% if forloop.last %}{{ image.src }}{% endif %}{% endfor %}

 

It will run through all the images until it gets to the last one, then grab the source URL for that last image. Hope this helps! 

Elise


Forum|alt.badge.img+1
  • Contributor II
  • 3 replies
  • October 31, 2022

Hi @elisegaines ,

 

How do we do the same with the 2nd, 3rd…, nth item?

 

I tried {% for image in item.product.images %}{% if forloop.index == 2 %}{{ image.src }}{% endif %}{% endfor %} but it doesn’t work.

 

Thanks for your help,
Robin


Forum|alt.badge.img+1
  • Contributor II
  • 3 replies
  • October 31, 2022

This seems to work {% for image in item.product.images %}{% if forloop.counter == 2 %}{{ image.src }}{% endif %}{% endfor %}