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!
Additional suggestions of my code is highly appreciated:
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('<th>Team</th>');
// Adds one header for each place
for (var i = 0; i < result.no_of_places; i++) {
theadTr.append('<th>' + (i + 1) + '</th>');
}
// Add teams and their result.
$.each(result.teams, function (index, value) {
var row = ['<tr><td>', index, '</td><td>'];
// Add if place is found or not.
$(this.done).each(function () {
if (this === true) {
row.concat(['<td>yes</td>']);
} else {
row.concat(['<td>no</td>']);
}
});
$('.scorestable tbody').append(row.join('') + '</tr>');
});
});
Simple HTML template:
<p></p>
<table class="scorestable">
<thead>
<tr></tr>
</thead>
<tbody></tbody>
</table>
Hints (or note to self, if you want)
I really learned alot from this simple snippet from Kevin B:
$.each(["foo","bar","foobar"],function(i,val){ console.log(typeof this,typeof i,typeof val); }); // OUTPUTS: // ======== // object number string // object number string // object number stringArrays are immutable (edit if I use wrong term) in javascript.
// So instead of: origArray.concat(['more', 'values']); // I need to write: origArray = origArray.concat(['more', 'values']);