whoAmi21
whoAmi21

Reputation: 105

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>

Upvotes: 0

Views: 606

Answers (3)

Paul Armstrong
Paul Armstrong

Reputation: 7156

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.

Upvotes: 2

Tommaso_zhou
Tommaso_zhou

Reputation: 41

So to separately display them I think you need do something like this:

{% for key in Object.keys(json.color) %}
  <li>{{ key }},{{json["color"][key]["prestock"]}}</li>
{% endfor %}

Sorry, I suppose you already have the color keys. Now I update the code, hope works.

Upvotes: 0

Anand Jha
Anand Jha

Reputation: 10714

In JavaScript you should do like

json.color.off-white  OR json['color']['off-white']

// it will give you an object like

{
   "inactive" : 0,
   "instock" : 5,
   "prestock" : 49
}

// check  alert(JSON.stringify(json.color.off-white));

This won't return an Array so you won't be able to loop through it.

further you can get value of inactive by accessing object like json.color.off-white.inactive

Upvotes: 0

Related Questions