【问题标题】:Loop through nested object properties nunjucks循环遍历嵌套对象属性 nunjucks
【发布时间】:2016-09-13 07:26:17
【问题描述】:

我有一个这样的嵌套对象

contract: {
        packages: [
            {
                servicePoint: {
                    productType: {
                        name: 'Name1'
                    }
                },
                packages: [
                    {
                        servicePoint: {
                            productType: {
                                name: 'Name1'
                            }
                        }

                    },
                    {
                        servicePoint: {
                            productType: {
                                name: 'Name2'
                            }
                        }

                    }

                ]
            }
        ]
    }

我想遍历嵌套对象并查找所有 productType.name 值(如果存在)。 并创建元素

<button type="button">{{ servicePoint.productType.name }}</button>

我可以做这样的事情

{% for servicePoint in contract.packages[0].packages[0].servicePoints %}

但它只会在第二层对象下找到属性。


我找到了一些解决方案

{% 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 ?

【问题讨论】:

    标签: javascript nunjucks


    【解决方案1】:

    您可以在推送前检查names 中是否已经存在名称。

    附:我不确定传递给模板“不平衡”结构是个好主意。因为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 %}
    

    【讨论】:

      猜你喜欢
      • 2014-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-08
      • 2017-05-12
      • 1970-01-01
      • 2020-01-31
      • 1970-01-01
      相关资源
      最近更新 更多