循环遍历嵌套对象属性nunjucks

时间:2016-09-13 07:26:17

标签: javascript nunjucks

我有一个像这样的嵌套对象

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?

1 个答案:

答案 0 :(得分:2)

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

P.S。我不确定是否传递给模板&#34;不平衡&#34;结构是个好主意。因为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 %}