javascript - 使用 JQuery 使用对象填充表

标签 javascript jquery html json html-table

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

假设我有这些数据

[{01/01/01, 10, 纽约}, {01/01/01, 15, 伦敦}, {01/01/01, 16, 罗马},{02/01/01 , 40, 纽约},{02/01/01, 25, 伦敦}, {02/01/01, 36, 罗马}]

我想使用 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");
    }

最佳答案

我的问题的解决方案是:

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

关于javascript - 使用 JQuery 使用对象填充表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25361699/

相关文章:

javascript - 固定宽度跨度,无内联 block

html - 如何让左边的div展开,右边的div宽度不变?

javascript - 延迟加载图像和 anchor

javascript - 将 JSON 转换为 ViewModel 并将 token 传递给 Controller

javascript - JavaScript 对这个 "(x > 0) - (x < 0) || +x;"的解释是什么

javascript - 删除元素的所有动态 'data attributes'

javascript - 冒号( :), 可以是……什么意思?类似于equal(=)?

javascript - MS Dynamics 事件响应 POST : 500 Internal Server Error

javascript - 为什么touchmove只能用于文档

php - MySQL通知: Undefined index: How to resolve