Issue
I have data something like
[
{
date: '20 Apr',
maths: [70, 80.5, 100],
science: [25, 20.1, 30]
},
{
date: '21 Apr',
maths: [64, 76, 80],
science: [21, 25, 27]
},
];
I want to display the data inside table with custom labels for subjects, so the output table I want is like this
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
The code I have tried can be found here. Is this possible to do it or is there any way I should restructure the data to have the desired output.
Solution
The default markup contains two heading rows and the first heading contains the "Date" cell.
Next, using the first mark object create the subject headings and "min", "val" & "max" sub headings.
Then loop over the subjects and fill the table body.
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>
Answered By - Som Shekhar Mukherjee
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.