javascriptnode.jsfor-in-loopswig-template

How to get same outputs with JavaScript and swig?


var json = {
"color" : {
    "off-white" : {
        "inactive" : 0,
        "instock" : 5,
        "prestock" : 49
    },
    "red" : {
        "prestock" : 50,
        "instock" : 10,
        "inactive" : 0
    }
  }
};

In JavaScript if I do

  for (var col in json.color) {
      result += col  + " = " + JSON.stringify(json.color[col].prestock)+ "\n";
  }

I can get "off-white" and "red" and all the sub-documents.

I did the same thing but it won't give me the same outputs. What else can I do?

To get the outputs of "off-white" and "red" I have to

{% for col in Object.keys(json.color) %}

But I can't access to sub-documents.

If I do

{% for col in json.color %}
<li>{{Object.keys(col)}}</li>

I get

<li>"off-white", "red"</li>

I need them separately, like:

<li>off-white</li>
<li>red</li>

Solution

  • In swig, you can get both the key and the value without using Object.keys:

    {% for key, val in json.color %}
      <li>{{ key }} = {{ val.prestock }}</li>
    {% endfor %}
    

    That should give you the same thing you're asking for in the JavaScript example.