Accessing Shopify product lists by index

If you've not tried to do it before, you'd expect that accessing a product or collection list by index is as simple as adding [index] after your variable, right? Well unfortunately in Shopify that won't work.

In most cases you probably won't need to query a product or collection list by index in Shopify, but every now and again you'll have an edge case where that would be really handy. Inspired by a chat with mansedan over at the Shopify Developers Discord server, and my old Building Better Liquid Arrays article I've found a way to convert product and collection lists to index-accessible arrays.

Here's the answer to your problems:

{% assign products_array = section.settings.products | compact %}
{% assign my_product = products_array[index] %}

Where does this work?

I've been able to get this working with product_list and collection_list section settings, and with product, collection and file list metafields.

I'd expect this will work anywhere else too - essentially what you're doing with the compact filter here is forcing Liquid to convert the value to an array so that it can strip empty values.