javascript - Loop through nested object properties nunjucks -


i have nested object this

contract: {         packages: [             {                 servicepoint: {                     producttype: {                         name: 'name1'                     }                 },                 packages: [                     {                         servicepoint: {                             producttype: {                                 name: 'name1'                             }                         }                      },                     {                         servicepoint: {                             producttype: {                                 name: 'name2'                             }                         }                      }                  ]             }         ]     } 

i loop through nested object , find producttype.name values if it's exists. , create elements

<button type="button">{{ servicepoint.producttype.name }}</button> 

i this

{% servicepoint in contract.packages[0].packages[0].servicepoints %} 

but find properties under second level of object.


i have found solution

{% if contract.packages.length > 0 %}         {% item in contract.packages %}             {% if item.servicepoints.length > 0 %}                 {% set names =     (names.push(item.servicepoints[0].producttype.name), names) %}             {% endif %}             {% if item.packages.length > 0 %}                 {% value in item.packages %}                         {% set names = (names.push(value.servicepoints[0].producttype.name), names) %}                 {% endfor %}             {% endif %}         {% endfor %}     {% endif %} 

but got new problem. if find same producttype.name, create 2 buttons same value.

how uniq producttype.name ?

you can check name exists in names before push.

p.s. i'm not sure passed template "unbalanced" structure idea. because set arr = (arr.push(item), arr) trick.

{% if contract.packages.length > 0 %} // can don't check length. it's not necessary.      {% item in contract.packages %}         {% if item.servicepoints.length > 0 %}             {% set names = (names.push(item.servicepoints[0].producttype.name), names) %}         {% endif %}          {% if item.packages.length > 0 %}             {% value in item.packages %}                 {% if names.indexof(value.servicepoints[0].producttype.name) == -1 %} // <=                     {% set names = (names.push(value.servicepoints[0].producttype.name), names) %}                 {% endif %} // <=             {% endfor %}         {% endif %}      {% endfor %}  {% endif %} 

Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -