接口返回的数据是这样的
{
"code": 0,
"msg": "ok",
"count": 114,
"data": [
{
"xsje": 93733.5,
"lr": 12515.68,
"ppmc": "振坤记",
"month": [
{
"201907": {
"xsje": 20459,
"lr": 2610.98
}
},
{
"201908": {
"xsje": 31291,
"lr": 5594.24
}
},
{
"201909": {
"xsje": 41983.5,
"lr": 4310.46
}
}
]
},
{
"xsje": "385.0000",
"lr": "10.0000",
"ppmc": "紫鸿",
"month": [
{
"201909": {
"xsje": 385,
"lr": 10
}
}
]
}
]
}
希望生成的表格是下边这样的
我的垃圾代码
<body>
<div class="" style="margin: 50px">
<div>
<table class="table layui-table" data-toggle="table">
</table>
</div>
</div>
</body>
<script>
$.ajax({
url: "/api/brandStats",
type: 'get',
success: function (data) {
if (data.code == 0) {
//OK
createTable(data.data);
} else {
console.log(data);
layer.msg(data.msg)
}
}
})
function createTable(data) {
for (i = 0; i < 1; i++) {
var th = `<thead><tr><th rowspan="2">品牌</th>`;
month = [];
for (var x in data[0]['month']) {
for (var y in data[0]['month'][x]) {
th = th + ` <th colspan="2">` + y + `</th>`;
month.push(y); //计算下边的销售额和利润的数量
}
}
temp = '';
for (i = 0; i < month.length; i++) {
temp += `<th>销售额</th><th>利润额</th>`;
}
th = th + ` <th rowspan="2">销售总额</th>
<th rowspan="2">利润总额</th>
</tr>
<tr>` + temp + `</tr></thead>`;
}
//console.log(data);
var tb = `<tbody>`;
//for (i = 0; i < data.length; i++) {
for (i = 0; i < 3; i++) {
tb += `<tr><td>` + data[i].ppmc + `</td>`; //品牌名称
flag = [];
for (let mo in month) { // ["201907", "201908"]
tmp = 0;
for (let x in data[i]['month']) {
for (var y in data[i]['month'][x]) {
console.log(y)
if (flag.indexOf(y) < 0) {
if (y == month[mo]) {
flag.push(y)
tb += `<td>` + data[i]['month'][x][y]['xsje'] + `</td>`;
tb += `<td>` + data[i]['month'][x][y]['lr'] + `</td>`;
tmp++;
} else if (tmp === 0) {
tb += `<td>0</td>`;
tb += `<td>1</td>`;
tmp++;
} else {
console.log('...')
}
}
//
}
console.log(data[i]['month'][x])
}
}
tb += `<td>` + data[i].xsje + `</td>`;
tb += `<td>` + data[i].lr + `</td></tr>`;
}
$('.table').append(th + tb);
//console.log(tb);
}
</script>
我弄了很长时间,但是因为有些数据在某个月份有数据,有些没有,所以有的会缺失一部分表格,像下边这样
希望有人帮忙解决一下,谢谢
没有数据的月份,做个判断月份为空的给个空的td标签不就可以了;为了保证表格完整性,td个数不能少