Mati Kowa Mati Kowa - 3 years ago 52
HTML Question

Javascript looping through elements and adding to table

I'm having trouble finding a solution that will help me loop through a bunch of elements and putting the chosen values into a table. I've been able to withdraw some values but the method isn't dynamic.

Here is an example:

var Table = {
"credit": {
"link": "site link",
"logoUrl": "logo url",
"message": "message"
},
"groups": [
{
"labels": [
{
"name": "Western Conference",
"type": "conference"
},
{
"name": "Central Division",
"type": "division"
}
],
"standings": [
{
"stats": [
{
"name": "gp",
"value": 20
},
{
"name": "w",
"value": 17
},
{
"name": "l",
"value": 0
},
{
"name": "gf",
"value": 64
},
{
"name": "ga",
"value": 37
},
{
"name": "gd",
"value": 27
},
{
"name": "pts",
"value": 37
}
],
"team": {
"id": 12345,
"link": "team link",
"name": "team name",
"shortName": "team"
}
},


This is the structure of the elements. So far I've used this:

document.getElementById("sGamesPlayed").innerHTML=Table.groups[0].standings[0].stats[0].value;


to withdraw values. However there are more teams, stats and divisions so I would need some kind of loop to go through the elements and put the into a dynamic table.

Answer Source

I would consider you to look at http://underscorejs.org/.

it provides a bunch of utility functions that could help you, for example, _.each() helps you loop through JSON properties.

for the sample objects you've given (after completing the missing brackets at the end),

_.each(Table.groups[0].standings[0].stats, function(stats){
    console.log(stats['name']+","+stats['value'])
})

gives me:

gp,20
w,17
l,0
gf,64
ga,37
gd,27
pts,37

how it works is that you provide the object you want as the first argument and the function that you give as the second argument will be called with each element of the first argument (Assuming it is a list).

I would also urge you to look at underscore templating that you can use to render your table where i put the console.log :

  1. http://net.tutsplus.com/tutorials/javascript-ajax/getting-cozy-with-underscore-js/
  2. http://scriptble.com/2011/01/28/underscore-js-templates/
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download