我有類似的資料
[
{
date: '20 Apr',
maths: [70, 80.5, 100],
science: [25, 20.1, 30]
},
{
date: '21 Apr',
maths: [64, 76, 80],
science: [21, 25, 27]
},
];
我想用主題的自定義標簽顯示表內的資料,所以我想要的輸出表是這樣的
date | maths | science
| min | val | max | min | val | max
20 Apr | 70 | 80.5| 100 | 25 | 20.1| 30
21 Apr | 64 | 76 | 80 | 21 | 25 | 27
我嘗試過的代碼可以在這里找到。這是否可以做到,或者有什么方法我應該重組資料以獲得所需的輸出。
uj5u.com熱心網友回復:
默認標記包含兩個標題行,第一個標題包含“日期”單元格。
接下來,使用第一個標記物件創建主題標題和“min”、“val”和“max”子標題。
然后遍歷主題并填充表格主體。
const marks = [
{ date: "20 Apr", maths: [70, 80.5, 100], science: [25, 20.1, 30] },
{ date: "21 Apr", maths: [64, 76, 80], science: [21, 25, 27] },
];
const table = document.getElementById("table");
const tableBody = document.getElementById("table-body");
const tableHeader = document.getElementById("table-header");
const tableSubHeader = document.getElementById("table-sub-header");
if (marks[0]) {
const { date, ...subs } = marks[0];
Object.keys(subs).forEach((sub) => {
const th = document.createElement("th");
th.textContent = sub;
th.setAttribute("colspan", 3);
tableHeader.appendChild(th);
["min", "val", "max"].forEach((subheading) => {
const th = document.createElement("th");
th.textContent = subheading;
th.setAttribute("scope", "col");
tableSubHeader.appendChild(th);
});
});
}
marks.forEach((mark) => {
const tr = document.createElement("tr");
const { date, ...subs } = mark;
const th = document.createElement("th");
th.textContent = date;
th.setAttribute("scope", "row");
tr.appendChild(th);
Object.keys(subs).forEach((sub) => {
const [min, val, max] = subs[sub];
tr.innerHTML = `<td>${min}</td><td>${val}</td><td>${max}</td>`;
});
tableBody.appendChild(tr);
});
body {
font-family: arial;
}
table {
table-layout: fixed;
width: 100%;
border-collapse: collapse;
}
td, th {
padding: 0.5em;
border: 1px solid black;
}
th {
text-transform: capitalize;
}
<table id="table">
<thead>
<tr id="table-header"><th rowspan="2" scope="col">Date</th></tr>
<tr id="table-sub-header"></tr>
</thead>
<tbody id="table-body">
</tbody>
</table>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/464712.html
標籤:javascript 数组 有角度的 打字稿
