cols
have a format like {"metric": 4940616.0, "title": "display"}
, so you need to iterate through it to assemble the <td>
elements:
const fn2 = (th, td) => {
heads = Object.keys(d.data[0]);
col = Object.values(d.data);
for (var header of heads) {
$(th).append(`<th>${header}</th>`);
}
for (var cols of col) {
$(td).append(`<tr>`);
for (var val of Object.values(cols)) {
$(td).append(`<td>${val}</td>`);
}
$(td).append(`</tr>`);
}
}
var d = {"id": 12345, "code": "final", "error": "", "data": [
{"metric": 4940616.0, "title": "display"},
{"metric": 5132162.0, "title": "platform"},
{"metric": 4954576.0, "title": "subscribers"},
{"metric": 4882217.0, "title": "unique_visitors"}
]};
var codes = 1;
$('#d').append(`<table border=1><thead>
<tr id='add_th_${codes}'></tr></thead>
<tbody id='td_${codes}'></tbody></table>`);
fn2(`#add_th_${codes}`, `#td_${codes}`);
td, th { background: #333; color: white; padding: 1px 4px; font-size :13px; font-family: segoe ui; border: none; } thead, table { border: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="d"></div>
Your cols
in forEach is again an object. Putting a for loop on its values should fix the issue:
const fn2 = (th, td) => {
$.getJSON(api, function(elem) {
elem.forEach(d => {
heads = Object.keys(d.data[0]);
col = Object.values(d.data);
heads.forEach(headers => {
$(th).append(`<th>${headers}</th>`);
});
let colCells = '';
col.forEach(cols => {
Object.values(cols).forEach(c => {
colCells += `<td>${c}</td>`;
});
$(td).append(`<tr>${colCells}</tr>`);
});
});
}
I have multiple json files that I am trying to load into tables inside multiple divs.
Here is my json format:
json1:
[
{
"id": 12345,
"code": "final",
"error": "",
"data": [
{
"metric": 4940616.0,
"title": "display"
},
{
"metric": 5132162.0,
"title": "platform"
},
{
"metric": 4954576.0,
"title": "subscribers"
},
{
"metric": 4882217.0,
"title": "unique_visitors"
}
}
json2
[
{
"run_id": 098765,
"code_title": "random",
"error": "",
"data": [
{
"col1": "abc",
"avg": 1,
"mean": 0,
"median": 3
},
{
"col1": "abc",
"avg": 1,
"mean": 2,
"median": 6
},
{
"col1": "abc",
"avg": 1,
"mean": 1,
"median": 6
}
]
}
]
JavaScript/jQuery Code:
const fn2 = (th, td) => {
$.getJSON(api, function(elem) {
elem.forEach(d => {
heads = Object.keys(d.data[0]);
col = Object.values(d.data);
heads.forEach(headers => {
$(th).append(`<th>${headers}</th>`);
});
col.forEach(cols => {
$(td).append(`<tr><td>${cols}</td></tr>`);
});
});
});
}
const fn = () => {
$('#d').append(`
<table border=1>
<thead>
<tr id='add_th_${codes}'>
</tr>
</thead>
<tbody id='td_${codes}'>
</tbody>
</table>
`);
fn2(`#add_th_${codes}`, `#td_${codes}`);
}
I am able to load the headers into the multiple tables but not able to add the data into it.
Is there a way to do that? What am I doing wrong?
This is what my current table for json1 looks like:

How do I populate the table? What am I doing wrong?