javascript - 将 json 对象数据与表头一起附加到表中
问题描述
我有多个 json 文件,我试图将它们加载到多个 div 内的表中。
这是我的json格式:
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 代码:
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}`);
}
我能够将标题加载到多个表中,但无法将数据添加到其中。有没有办法做到这一点?我究竟做错了什么?
这是我当前的 json1 表的样子:
如何填充表格?我究竟做错了什么?
解决方案
cols
有一个格式{"metric": 4940616.0, "title": "display"}
,所以你需要遍历它来组装<td>
元素:
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>
推荐阅读
- javascript - 每个 React 组件仅获取一次数据
- excel - vba中的手动日期选择
- r - r 中小于 1000 的孪生素数
- kotlin - 对象类中的 Kotlin LiveData
- javascript - Javascript - 如何在 Object 构造函数中从字典中检索键
- php - AMP - 如何以编程方式调用点击事件处理程序?
- django - 提供受保护的文件 NGINX 和 Django
- javascript - Mongoose 复合唯一键索引似乎不起作用
- paypal - 贝宝账单协议令牌
- javascript - jQuery MS Edge:trigger('blur') 为箭头、退格和删除保持焦点