我有一个条件,需要我使用json多维创建一个html表。这是我的JSON数据的示例
let year = [
{
ym : "202006",
data : [
{
202007: "100",
202008: "100",
202009: "100",
202010: "100",
202011: "96.71",
202012: "100",
202101: "100",
202102: "96.43"
}
]
}
];这是我期望的结果

我已经成功地使用循环创建了表头。但是,我发现使用这个JSON数据生成表数据是很困难的。任何形式的帮助都将是真正的学徒。谢谢
编辑:
我能够使用原始数据生成表头。我使用的代码是
result = arr.reduce(function (r, a) {
r[a.TIME_PERIOD_HEADER] = r[a.TIME_PERIOD_HEADER] || [];
r[a.TIME_PERIOD_HEADER].push(a);
return r;
}, Object.create(null));
var keys = Object.keys(result);
keys.map((value, index) => {
$('#tbl_row').append('<th>'+value+'</th>')
})生成表头后,我尝试使用以下方法将原始json数组修改为新的json数组:
var o = arr.reduce( (a,b) => {
a[b.TIME_PERIOD] = a[b.TIME_PERIOD] || [];
a[b.TIME_PERIOD].push({[b.TIME_PERIOD_DATA]:b.PERCENT});
return a;
}, {});
var a = Object.keys(o).map(function(k) {
var m = Object.assign.apply({},o[k]);
keys.forEach( (x) => { if ( !(x in m) ) m[x] = 0 });
return {TIME_PERIOD: k, TIME_PERIOD_DATA: m};
});
//this code produce the first JSON data (let year = ....)发布于 2021-06-23 08:20:26
下面的代码段忽略了data是一个数组,因为您的预期输出也忽略了它。
let year = [
{
ym : "202006",
data : [
{
202007: "100",
202008: "100",
202009: "100",
202010: "100",
202011: "96.71",
202012: "100",
202101: "100",
202102: "96.43"
}
]
}
];
let columns = year
.map (y => y.data)
.flat (1)
.map (d => Object.keys(d))
.flat (1)
.sort ()
.filter ((x, i, a) => !i || x != a[i-1]);
document.write ('<table><tdata>');
document.write ('<tr style="text-transform: uppercase">');
document.write ('<th rowspan="2">time period</th>');
document.write (`<th colspan=${columns.length}>time period data</th>`);
document.write ('</tr></tr>');
for (const c of columns) {
document.write (`<td>${c}</td>`);
}
document.write ('</tr>');
for (const y of year) {
document.write (`<tr><td>${y.ym}</td>`);
for (const c of columns) {
document.write (`<td>${y.data[0][c]}</td>`);
}
document.write ('</tr>');
}
document.write ('<tdata><table>');
其思想是:对所有数据进行迭代以计算列列表。在此之后,在多年内并在每年迭代列,以便从列的数据中选择正确的值。排序后的筛选器使排序列表唯一,因为代码从所有数据对象收集所有列。
https://stackoverflow.com/questions/68094988
复制相似问题