skip to Main Content

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 here
enter 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?

3

Answers


  1. not sure what you’re trying to achieve but have a look at the Array.of method.

    Array.of({obj1Prop1: 'value1'}, { obj2Prop1: 'value2'});
    

    nevertheless – it looks like your collections are actually a collection and you therefore you maybe looking for an array in a higher scope defined and just push / concat them together once you reach your code with your collection.

    Login or Signup to reply.
  2. 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 %}
    
    Login or Signup to reply.
  3. The object is probably more useful in most cases but you can so something like this:

    <script>
      var collections = {
    
        "collections": [{% for collection in collections %}
          {
          {% if collection.image %}"image": "{{ collection.image }}",{% endif %}
          "body_html": "{{ collection.description | url_escape }}",
          "handle": "{{ collection.handle }}",
          "id": {{ collection.id }},
          "sort_order": "{{ collection.default_sort_by }}",
          "template_suffix": "{{ collection.template_suffix }}",
          "title": "{{ collection.title }}",
          "products_count": {{ collection.products_count }},
          "url": "{{ collection.url }}",
          "products": []
          }{% unless forloop.last %},{% endunless %}{% endfor %}
        ]
      }
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search