The following codes generate table row dynamically. I wonder if there are better ways of generating the same data. Also instead of manually coding the heading and the table itself, is it possible to code them with less codes without using the innerHTML function.
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Mark Score</th>
</tr>
</thead>
</table>
Data:
const students = {
'24': {
'id':'24',
'Name':'Zuali',
'mark':30,
},
'25': {
'id':'25',
'Name':'Famkima',
'mark':52,
},
'27':{
'id':'27',
'Name':'Duha',
'mark':77,
},
'28':{
'id':'28',
'Name':'Rema',
'mark':81,
},
'29':{
'id':'29',
'Name':'Sanga',
'mark':47,
},
'30':{
'id':'30',
'Name':'Dari',
'mark':23,
},
};
JS code to create the table data:
const markObtained = Object.keys(students).reduce(function(names, name) {
if (students[name].mark>=20) {
names[name] = students[name];
}
return names;
}, {});
const doc = document.createDocumentFragment();
const table = document.querySelector("table");
for(let i=0; i<Object.keys(markObtained).length; i++) {
const data = Object.values(markObtained)[i];
const tr = document.createElement("tr");
for (const v in data){
const td = document.createElement("td");
td.textContent = data[v];
tr.appendChild(td);
}
table.appendChild(tr);
}
table.appendChild(doc);
I would highly appreciate if any expert in js can help me better optimize the codes and give me another workaround examples?