loop through metafields appending _indexNumber in liquid that need to be assigned to an object value to match to a specific key

Viewed 1065

I have a dynamic number of metafields coming into Shopify. I have a special metafield that tells me how many metafield files to look for and I use that to specify the loop amount.

I need to loop through these metafields and look for a specific matching key.

numfiles variable here is coming from that metafield that gives me the number of total metafield files to loop through.

I have tried:

{% for i in (1..numfiles) %}
 {% assign currentMetafield = 'shop.metafields.field_name.value_name_' | append: i %}
 {% if currentMetafield['key_i_am_matching'] %}
  found a match
 {% else %}
  no match found :(
 {% endif %}
{% endfor %}

However this doesn't work, my guess is that it doesn't work because the assigned currentMetafield is ultimately a string.

I've tried to print out the value coming from the loop {{currentMetafield}} and the output of that is correctly matched to my metafield names. It looks like this:

shop.metafields.field_name.value_name_1
shop.metafields.field_name.value_name_2
shop.metafields.field_name.value_name_3

If I manually assign the metafield and look for a specific key, that works just fine.

Say I know a specific key is in the first metafield file. I can just assign it like so

{% assign metafield1 = shop.metafields.field_name.value_name_1 %}

then i can do this:

{% if shop.metafields.field_name.value_name_1['key_i_am_looking_for'] %}
  found a match
{% end if %}

This returns found a match predictively.

I either need to turn this string into an object so that shopify recognizes it as a proper metafield file, or I need to do something else to try to find a match in a dynamic amount of metafields.

Thanks for the help!

1 Answers

you need to use capture for the dynamic value. try this code

{% for i in (1..numfiles) %}
{% capture value %}value_name_{{i}}{% endcapture %}
 {% assign currentMetafield = shop.metafields.field_name[value]%}
 {% if currentMetafield['key_i_am_matching'] %}
  found a match
 {% else %}
  no match found :(
 {% endif %}
{% endfor %}
Related