I was working with a table in HTML and I have the following doubt: I am taking the data from a JSON array: {"key":["1","2","3"],"values":["4","5","6"]}
and when trying to insert them into the table instead of putting each data in a column all the data is put in the first column, the JS code that I am using to insert the data in the table is:
var idtabla = document.getElementById("idtabla")
idtabla.innerHTML = window.location.href.split("/tabla/")[1]
function getJson(){
var id = window.location.href.split("/tabla/")[1]
var table = document.getElementById("table")
$.get( `/json`, (data) => {
if(data.error){
idtabla.innerHTML = 404 ", tabla no encontrada"
} else {
var keys = data.key.forEach(element => {
table.innerHTML = `<tr><td>${element}</td>`
});
var values = data.values.forEach(element => {
table.innerHTML = `<td>${element}</td></tr>`
});
}
})
}
and the result it gives me is this:
How could it be solved? Thanks a lot.
CodePudding user response:
There are two problems.
First, you can't add partial HTML to innerHTML
like that. Whenever you assign to innerHTML
, it parses the result completely. If there are any unclosed tags, they're closed automatically. If you want to build the HTML incrementally, you should do it by appending to a string, then assign the completed string to innerHTML
.
Second, you're appending all the values all the values after all the keys, so they won't be in matching rows. You need to append both the key and value in the same loop. Since forEach()
passes the array index to the callback function, you can use that to index into the other array.
let tableHTML = '';
data.keys.forEach((key, i) => {
tableHTML = `<tr><td>${key}</td><td>${data.values[i]}</td></tr>`;
});
table.innerHTML = tableHTML;