gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:42:04 26 4
gpt4 key购买 nike

我有一个对象数组 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com