chrisdeb chrisdeb - 1 year ago 60
HTML Question

Populating a table with an object with JQuery

I have an array of objects object

[{Date, Count, City}]


Lets say I have this data

[{01/01/01, 10, New York}, {01/01/01, 15, London}, {01/01/01, 16, Rome},{02/01/01, 40, New York},{02/01/01, 25, London}, {02/01/01, 36, Rome}]


I want to populate an html table using JQuery and have the following result

Date | New York | London | Rome
01/01/01 | 10 | 15 | 16
02/01/01 | 40 | 25 | 36


Is it possible to generate a table similar to this with JQuery?

This is the code I have done so far

for (var i = 0; i < countResult.length; i++) {
var html = "<table><thead><tr><th>Date</th><th>City</th><th>Count</th></thead><tbody>";
for (var j = 0; j < countResult[i].length; j++) {
html += "<tr>";
html += "<td>" + countResult[i][j].date + "</td><td>" + countResult[i][j].city + "</td><td>" + countResult[i][j].count+ "</td>";
}
html += "</tr>";

html += "</tbody></table></br>";
$(html).appendTo("#div");
}

Answer Source

The solution for my question was:

    var countResult = [    
      ["01/01/01", 10, "New York"],    
      ["01/01/01", 15, "London"],     
      ["01/01/01", 16, "Rome"],     
      ["02/01/01", 40, "New York"],     
      ["02/01/01", 25, "London"],    
      ["02/01/01", 36, "Rome"]     
    ]  
    var cities = []

   $.each(countResult, function(rowNum, row) {
       var city = row[2];      
       if($.inArray(city, cities) < 0) cities.push(city);      
   });

    var html = "<table><thead><tr><th>Date</th>"
       + $.map(cities, function (c) {      
           return "<th>" + c      
    }).join("") + "</tr></thead><tbody>";          

    var summary = {};

    $.each(countResult, function
      (rowNum, row) {      
        if(!summary[row[0]]) summary[row[0]] = {}    
        summary[row[0]][row[2]] = row[1];      
    });

    $.each(summary, function (date, counts) {     
        html += "<tr><td>" + date;
        $.each(counts, function (i, ct) {     
           html += "<td>" + ct     ; 
        });      
        html += "</tr>";      
    });      
    $(html).appendTo("#div");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download