Search code examples
jsonnode.jsmongodbexpressswig-template

swig-template testing condition with subdocument


I have a json:

var json = [{
        a: "asdf",
        b: "a",
        c: {1:{z:30,x:20,y:50},2:{z:30,x:50,y:30}}
    },
    {
        a: "fdsa",
        b: "o",
        c: {1:{z:10,x:20,y:50},2:{z:0,x:20,y:30}}
    }
]

I want to have a condition to check:

  • if any item z, x, or y in the c object is greater than 30, show the value for a

Is this possible? I did some research but couldn't find any answers. Please help! Thanks! I tried

{% for c,b in json.c %}

Solution

  • Your use case is incredibly complex and probably better done server-side, but here's a way you can do it in swig...

    {% for item in json %}
      {% set show = false %}
      {% for set in item.c %}
        {% for k in set %}
          {% if k > 30 %}
            {% set show = true %}
          {% endif %}
        {% endfor %}
      {% endfor %}
      {% if show %}
        {{ item.a }}
      {% endif %}
    {% endfor %}