shopifyliquid

How can I loop over an array and store the data in a variable in liquid?


I'm doing the following using JS with liquid:

const variantsWithInventoryData = {};

// Loop through each variant and assign to the object
{% for variant in product.variants %}
  variantsWithInventoryData["{{ variant.id }}"] = {
    inventory_quantity: {{ variant.inventory_quantity }},
    inventory_policy: "{{ variant.inventory_policy }}",
    inventory_management: "{{ variant.inventory_management }}",
    inventory_item_id: 0
  };
{% endfor %}

How can I achieve the above entirely using liquid?

Thanks!


Solution

  • 1st I've looped over the variants using only liquid inside a script with a id and then I fetched the required data by parsing the data inside that script element. Here's the implementation:

    {% comment %} Separate Liquid Code START {% endcomment %}
    <script type="application/json" id="inventory-data">
      {
        {% for variant in product.variants %}
          "{{ variant.id }}": {
            "inventory_quantity": {{ variant.inventory_quantity }},
            "inventory_policy": "{{ variant.inventory_policy }}",
            "inventory_management": "{{ variant.inventory_management }}",
            "inventory_item_id": 0
          }
          {% unless forloop.last %},{% endunless %}
        {% endfor %}
      }
    </script>
    
    <script>
      // Fetch the JSON from the script tag
      const inventoryDataFromElement = document.getElementById('inventory-data');
      let varsWithInventoryData;
    
      varsWithInventoryData = JSON.parse(inventoryDataFromElement.textContent);
      window.varsWithInventoryData = varsWithInventoryData;
      console.log(varsWithInventoryData); 
    </script>
    {% comment %} Separate Liquid Code END {% endcomment %}