Access product list metafields by index not working

For some reason, it seems we can’t access some metafields list by index.

For instance, this works as expected for single_line_text_field in list:

{{ product.metafields.namespace.key.value[0] }} => my first value
{{ product.metafields.namespace.key.value[1] }} => my second value

But it doesn’t work for product_reference in list, unless for the first and last filters:

{{ product.metafields.namespace.key.value[0] }} => 
{{ product.metafields.namespace.key.value[1] }} => 
{{ product.metafields.namespace.key.value | first }} => ProductDrop (working)

I tried multiple array filters such as map and such, but it seems only a standard for loop allows to access product_reference in list, which can be annoying.

It looks like a bug, and if not what array filters should we use to avoid doing a for loop and access it with index variable.

I’m running into the same issue, apparently, when trying to access a single object in a list to pass it as a section setting.

The following code throws an error (“Dynamic source ‘collection.metafields.custom.highlighted_products.value|first’ is type: Product List. Setting ‘product’ can only use type: Product”).

"highlighted-product-1": {
      "type": "product--highlighted-product",
      "settings": {
        "product": "{{ collection.metafields.custom.highlighted_products.value[0] }}",
        "image-width": "medium",
        "layout": "left"
      }
    }

Note that, in my case, even the ‘first’ filter breaks.

Here’s a solution (double reverse filter) :

{%  assign my_product = product.metafields.custom.product_list.value | reverse | reverse %}
Product title: {{ my_product[1].title }}

Credits goes to @Masserra . We discussed this “trick” more in depth on a github issue here. This way we can access a list of object references (products, collections etc.) with metafields using only this one-liner piece of code.

Thanks for this insane hack/tip! Was pulling my hair out trying to reference a file list!

This is the most unnecessary overhead workaround that actually does work. Really sad that this hasn’t been fixed for 1.5 years…

Thanks for the hack!

Yes, liquid has a lot of shortcomings! I’ve read in a blog posts that

{%  assign my_product = product.metafields.custom.product_list.value | compact %}

also works, but haven’t tried it myself. Still a hack but you’d save one filter :wink:

Nice one! The compacter the better… :sweat_smile:

Can confirm compact works as well.

Thanks!

Ugh, thank you. Amazing we even have to use that filter just to grab an item by index from an array.