Javascript 通过嵌套对象属性NUNJUCK循环
我有一个像这样的嵌套对象Javascript 通过嵌套对象属性NUNJUCK循环,javascript,nunjucks,Javascript,Nunjucks,我有一个像这样的嵌套对象 contract: { packages: [ { servicePoint: { productType: { name: 'Name1' } }, packages: [
contract: {
packages: [
{
servicePoint: {
productType: {
name: 'Name1'
}
},
packages: [
{
servicePoint: {
productType: {
name: 'Name1'
}
}
},
{
servicePoint: {
productType: {
name: 'Name2'
}
}
}
]
}
]
}
{% for servicePoint in contract.packages[0].packages[0].servicePoints %}
我希望通过嵌套对象进行循环,并查找所有productType.name值(如果存在)。
并创建元素
<button type="button">{{ servicePoint.productType.name }}</button>
但它只能在对象的第二级下找到属性
我找到了一些解决办法
{% if contract.packages.length > 0 %}
{% for 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 %}
{% for value in item.packages %}
{% set names = (names.push(value.servicePoints[0].productType.name), names) %}
{% endfor %}
{% endif %}
{% endfor %}
{% endif %}
但我遇到了新问题。如果找到相同的productType.name,它将创建两个具有相同值的按钮
如何uniq productType.name?在推送之前,您可以检查名称是否已存在于
名称中
另外,我不确定传递到模板的“不平衡”结构是个好主意。因为set arr=(arr.push(item),arr)
是一个技巧
{% if contract.packages.length > 0 %} // You can don't check length. It's not a necessary.
{% for 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 %}
{% for 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 %}
{%if contract.packages.length>0%}//您不能检查长度。这不是必要的。
{contract.packages%中项目的%s}
{%if item.servicePoints.length>0%}
{%set name=(names.push(item.servicePoints[0].productType.name),names)%}
{%endif%}
{%if item.packages.length>0%}
{item.packages%中的值为%1}
{%if names.indexOf(value.servicePoints[0].productType.name)=-1%}//