Note that there are some explanatory texts on larger screens.

plurals
  1. POLoop over json array inside dict
    primarykey
    data
    text
    <p>I really suck at javascript, but you have to learn. I'm trying to loop thru a json string to build a table. It's working (kind of). But one piece is not working. I try to loop thru an array of booleans. If it's true, add a column with the text "yes", if it's false add one with "no". But that part won't work. It won't add any values at all!</p> <p>Additional suggestions of my code is highly appreciated: </p> <pre><code>var jsonstr = '{"no_of_places": 4, "teams": {"Player 1": {"done": [true, true, true, false], "time": null}, "Player 2": {"done": [true, true, true, true], "time": "0 dagar 1:10:21"}, "Player 3": {"done": [true, true, true, true], "time": "0 dagar 2:47:34"}}}'; $(document).ready(function () { var result = jQuery.parseJSON(jsonstr); var theadTr = $('.scorestable thead tr'); theadTr.append('&lt;th&gt;Team&lt;/th&gt;'); // Adds one header for each place for (var i = 0; i &lt; result.no_of_places; i++) { theadTr.append('&lt;th&gt;' + (i + 1) + '&lt;/th&gt;'); } // Add teams and their result. $.each(result.teams, function (index, value) { var row = ['&lt;tr&gt;&lt;td&gt;', index, '&lt;/td&gt;&lt;td&gt;']; // Add if place is found or not. $(this.done).each(function () { if (this === true) { row.concat(['&lt;td&gt;yes&lt;/td&gt;']); } else { row.concat(['&lt;td&gt;no&lt;/td&gt;']); } }); $('.scorestable tbody').append(row.join('') + '&lt;/tr&gt;'); }); }); </code></pre> <p>Simple HTML template:</p> <pre><code>&lt;p&gt;&lt;/p&gt; &lt;table class="scorestable"&gt; &lt;thead&gt; &lt;tr&gt;&lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt;&lt;/tbody&gt; &lt;/table&gt; </code></pre> <h3>Hints (or note to self, if you want)</h3> <ol> <li><p>I really learned alot from this simple snippet from Kevin B:</p> <pre><code>$.each(["foo","bar","foobar"],function(i,val){ console.log(typeof this,typeof i,typeof val); }); // OUTPUTS: // ======== // object number string // object number string // object number string </code></pre></li> <li><p>Arrays are immutable (edit if I use wrong term) in javascript.</p> <pre><code>// So instead of: origArray.concat(['more', 'values']); // I need to write: origArray = origArray.concat(['more', 'values']); </code></pre></li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload