Manipulating objects inside for loop

Hello,

I’m struggling with these two cases, inside nested loops I can’t update directly the object, nor checking for the array that I’m populating.
Note that ALL_PRODUCTS, ALL_VARIANTS, ALL_SKU are all HubDb table rows.

Are there any workaround? I need to update the top object in the hierarchy, based on properties that are present in nested children objects.

{% set PRODUCTS = [] %}
{% for product in ALL_PRODUCTS %}
 {% for v in ALL_VARIANTS %}
 {% if v.idproduct == product.id_ls %}
 {% for s in ALL_SKU %}
 {% if s.idvariant == v.id_ls and s.publishing != 'n' %}
 {# TRYING TO UPDATE DIRECTLY THE OBJECT I'M LOOPING THROUGH, DOESN'T WORK #}
 {% do product.update({'batterie_input': s.batterie_input}) %}

 {% do PRODUCTS.append(product) %}

 {# TRYING TO CHECK THE UPDATED ARRAY AFTER APPEND, DOESN'T WORK, IT ONLY WORKS AFTER THE LOOP HAS FINISHED #}
 {{ PRODUCTS }}
 {% endif %}
 {% endfor %}
 {% endif %}
 {% endfor %}
{% endfor %}

Hey, @EnriAlea :waving_hand: This is the expected outcome based on how HubL doesn’t allow direct updates on objects inside loops. Have you looked into:

  • Creating a temporary copy, e.g. `product_copy` to update in the nested loops
  • Use `merge` to ass properties
  • Append `product_copy` to PRODUCTS outside your inner loops

If you’ve already gone down this road, please let me know, and we can try tagging in a few champions who have HubL experience.

Thanks! — Jaycee

Hi @EnriAlea,

When working with nested loops in HubL, there are two main limitations:

  1. Direct object updates inside loops are not supported
  2. Array checks during loop iteration are not possible until after the loop completes

To work around these limitations, you can try:

  1. Create new objects instead of modifying existing ones
  2. Collect all necessary data first, then process it outside the loops
  3. Use intermediate arrays to store temporary results

For example:

{% set PRODUCTS = [] %}
{% set temp_product = {} %}
{% for product in ALL_PRODUCTS %}
 {% do temp_product.update(product) %}
 {# Collect modifications in temporary object #}
 {% do PRODUCTS.append(temp_product) %}
{% endfor %}

Hi!

your suggestion does the trick, but I have to create the temp object inside the first loop.

Thx!

Enrico