我有一个 JSON 数据,如下所示。我需要使用 javascript 从此 JSON 生成一个表。对我来说最难的部分是将每个元素显示为一列。请帮我解决这个问题。
JSON:
[
{
"Header": "Column1",
"Values": [
"75",
"79",
"83"
]
},
{
"Header": "Column2",
"Values": [
"77",
"81",
"86",
"90"
]
},
{
"Header": "Column3",
"Values": [
"98",
"117"
]
}
]
我想以下表格式显示此数据
|Column1|Column2|Column3|
-------------------------
| 75 | 77 | 98 |
| 79 | 81 | 117 |
| 83 | 86 | |
| | 90 | |
实现这一目标的最佳方法是什么?
最佳答案
您可以首先获取表的标题,然后在迭代列名称时,您可以收集每个数据数组的长度并获取其最大长度,以便稍后迭代 td
元素。
var data = [{ Header: "Column1", Values: ["75", "79", "83"] }, { Header: "Column2", Values: ["77", "81", "86", "90"] }, { Header: "Column3", Values: ["98", "117"] }],
table = document.createElement('table'),
tr = document.createElement('tr'),
rows = [],
max = 0,
i;
table.appendChild(tr);
data.forEach(function (o) {
var th = document.createElement('th');
th.appendChild(document.createTextNode(o.Header));
tr.appendChild(th);
max = Math.max(max, o.Values.length);
});
for (i = 0; i < max; i++) {
tr = document.createElement('tr'),
table.appendChild(tr);
data.forEach(function (o) {
var td = document.createElement('td');
tr.appendChild(td);
td.appendChild(document.createTextNode(i in o.Values ? o.Values[i] : ''));
});
}
document.body.appendChild(table);
关于javascript - 在javascript中从json数组动态生成表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43775947/