Adding objects to array using shopify liquid

Adding objects to array using shopify liquid

biocule
Excursionist
38 0 7

Hi Guys, I am trying to create object using 2 metafields present on the collection. I am able to create the object but when I try to insert in an array (i.e to finally get an array with objects) I always get empty array. I believe there is some thing small mistake I am not able to identify. Below is my code Can someone please help:

 

{% assign collectionImageList = collection.metafields.custom.testing_list_image.value %}

{% assign collectionValueList = collection.metafields.custom.testing_list_value.value %}

{% assign objects = '[]' | json %}

{% assign i = 0 %}

{% for image in collectionImageList %} {% assign bannerWithLink = '{"immagesrc": "' | append: image.src | append: '", "bannerlink": "' | append: collectionValueList[i] | append: '"}' | json %}

{% assign objects = objects | push: bannerWithLink | json %}

{% assign i = i | plus: 1 %}

{% endfor %}

<p>{{ objectsArray }}</p>

Replies 3 (3)

biocule
Excursionist
38 0 7

Can anyone help me with in solving above problem. It would be of great help!

nadinethery
Shopify Partner
19 1 6

Hi there!

 

Maybe I'm late, but in your code I see a couple of things:

 

1. You reference `objectsArray` but I don't see this variable is declared anyway in the code above.

 

2. You are using 'push'  as a filter, but as far as I know, this is not a valid Liquid filter, so I don't think that is doing what you expect it to do, like in Javascrip. Liquid in general is not made to work with arrays like other languages do. 

 

If you are looking to concatenate or modify arrays in Liquid, I recommend this post, that actually helped me in a similar case.

 

Building better arrays in Liquid 

 

red_lebowski
Shopify Partner
1 0 0

Hey Biocule!

 

I know this might be a bit late for you but hopefully this helps out anyone else that comes through. 

I think i see what you're trying to do and it's worthing noting that this isn't my solution but something I picked up from Braze, see below:

 

-- initialise an empty array
{% assign my_new_array = "" | split: ""%}
{% for item in my_array %}
-- apply whatever filtering you'd like
{% if item.thing == 'something' %}
-- this is the clever bit
-- you can use concat (not append) which joins two arrays, so instead of appending 
-- the item directly, you slice it out which creates an array of 1 and concat the rest
-- of the array back to it!
{% assign my_new_array = my_array | slice: forloop.index0 | concat: my_new_array %}
{% endif %}
{% endfor %}
{% assign my_new_array = my_new_array | reverse %}