Ad

Cast Multiple Objects To An Array

Im looping through some collections (called categories in Shopify Liquid), and I need to cast all those collections into an array, so I can access their indexes.

What Im doing now is this:

{% for link in linklists[page.handle].links limit:1 %}
 {% assign collection = link.object %}

 // Im doing the above code somewhere above in the liquid file, thats where I get the link.object


<script>
  var collections = {{ link.object | json }};
  console.log(collections);
</script>

And this is the result I get:

enter image description here

I need the result to be like this, in an array: enter image description hereenter image description here

How can I cast those set of objects to array like I have shown for the images below?

/********** EDIT *******/

When I use Array.of(), like this:

console.log(Array.of(collections));

I get this: enter image description here

But all those Objects are still not in an array. Maybe push it up one level?

Ad

Answer

Why are you initiating the collections variable inside the for loop? Try this

<script>var collections = new Array</script>
{% for link in linklists[page.handle].links limit:1 %}
 {% assign collection = link.object %}

 // Im doing the above code somewhere above in the liquid file, thats where I get the link.object


<script>
  collections.push({{ link.object | json }});
  console.log(collections);
</script>
{% endfor %}
Ad
source: stackoverflow.com
Ad