使用JQuery填充带有对象的表

时间:2014-08-18 10:58:46

标签: javascript jquery html json html-table

我有一个对象数组[{Date, Count, City}]

让我说我有这个数据

[{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}]

我想使用JQuery填充html表并获得以下结果

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

是否可以使用JQuery生成与此类似的表?

这是我到目前为止所做的代码

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");
    }

2 个答案:

答案 0 :(得分:1)

我的问题的解决方案是:

    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");

答案 1 :(得分:0)

试试此代码

            var html='<table>';
            var arObj = YOUR ARRAY OBJECT;
                $(arObj).each(function(i, u) {

                    var Date = u[0];
                    var count = u[1];
                    var City=u[2];
                   html=html+'<tr><td>'+Date+'</td><td>'+count+'</td><td>'+City+'</td><td>';

                });
            html=html+'</table>';

现在附加到html

$('#myDiv').append(html);