Actualmente estoy recibiendo datos JSON y quiero formatearlos en una tabla usando javascript y html. Cualquier ayuda es apreciada.
Los datos JSON que recibo después de una solicitud de captura tienen este aspecto:
{
"results": [
{
"studentId": "Damien.Hammes93",
"score": 0.778678577215454
},
{
"studentId": "Beverly56",
"score": 0.7879353094963757
},
{
"studentId": "Tyshawn37",
"score": 0.723347659626473
},
]
}
Así es como quiero que la tabla formatee:
<table>
<tr>
<th>Student ID</th>
<th>Grade</th>
</tr>
<tr>
<td>Damien.Hammes93</td>
<td>0.778678577215454</td>
</tr>
<tr>
<td>Beverly56</td>
<td>0.7879353094963757</td>
</tr>
<tr>
<td>Tyshawn37</td>
<td>0.723347659626473</td>
</tr>
</table>
Así es como se ve actualmente mi código:
window.addEventListener('load', async() => {
const studentsTableTag = document.getElementById("studentsTable");
// studentsTableTag selects the student <table>
const studentsData = await receivesExamOrStudentData(enpoints['students']);
//studentsData returns the students JSON listed above
const studentsTable = (ele) => {
let html = `<table><tr>`;
html += `<td id="studentID" > ${ele} </td>`;
html += `</tr></table>`;
return html
}
const htmlStudents = studentsData.map(student =>
`<tr>${studentsTable(student)}</tr>`
).join('')
studentsTableTag.innerHTML = htmlStudents
})
2 respuestas
Sugeriría usar algunos motores de plantillas para eso. Ej .: bigote, manillar, etc. Te hace la vida más fácil si tienes que hacer esto por diferentes cosas
Te faltan algunas cosas. 1. No es necesario agregar un elemento de tabla para cada elemento del alumno 2. Olvidaste agregar los encabezados 3. ${ele}
es un objeto, debe imprimir dos td
s para studentId y grade
window.addEventListener('load', async () => {
const studentsTableTag = document.getElementById("studentsTable");
// studentsTableTag selects the student <table>
const studentsData = {
"results": [{
"studentId": "Damien.Hammes93",
"score": 0.778678577215454
},
{
"studentId": "Beverly56",
"score": 0.7879353094963757
},
{
"studentId": "Tyshawn37",
"score": 0.723347659626473
},
]
}
//studentsData returns the students JSON listed above
const studentsTable = (ele) => {
let html = ``;
html += `<td class="studentID" > ${ele.studentId} </td>`;
html += `<td class="score" > ${ele.score} </td>`;
return html
}
const htmlStudents = studentsData.results.map(student =>
`<tr>${studentsTable(student)}</tr>`
).join('')
studentsTableTag.innerHTML = '<tr><th>Student ID</th><th>Grade</th></tr>' + htmlStudents;
})
<table id="studentsTable"></table>
Nuevas preguntas
javascript
Para preguntas sobre la programación en ECMAScript (JavaScript / JS) y sus diversos dialectos / implementaciones (excepto ActionScript). Incluya todas las etiquetas relevantes en su pregunta; por ejemplo, [node.js], [jquery], [json], etc.