【发布时间】:2021-07-27 23:00:17
【问题描述】:
我有一个对象数组。我想用对象数组中的值填充我的表:
这是我的代码:
let data = [
{cat: 'one', device: 'iphone', site: 'google', val1:10, val2:20, val3:30},
{cat: 'two', device: 'iphone', site: 'bing', val1:23, val2:12, val3:14},
{cat: 'three', device: 'iphone', site: 'jeeves', val1:67, val2:78, val3:12},
{cat: 'four', device: 'ipad', site: 'google', val1:10, val2:20, val3:30},
{cat: 'five', device: 'ipad', site: 'bing', val1:23, val2:12, val3:14},
{cat: 'six', device: 'ipad', site: 'jeeves', val1:67, val2:78, val3:12},
{cat: 'seven', device: 'mac', site: 'google', val1:10, val2:20, val3:30},
{cat: 'eight', device: 'mac', site: 'bing', val1:23, val2:12, val3:14},
{cat: 'nine', device: 'mac', site: 'jeeves', val1:67, val2:78, val3:15}
]
let heads = Object.keys(data[0]);
heads.forEach(d => $(`#headers`).append(`<td>${d}</td>`));
data.forEach(td => {
$(`#body_deets`).append(`<tr></tr>`);
heads.forEach(th => {
$(`#body_deets > tr`).append(`<td>${td[th]}</td>`);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class='table' border=1>
<thead><tr id='headers'></tr></thead>
<tbody id='body_deets'></tbody>
</table>
如您所见,当我尝试在表中追加数据时,所有数据都添加到一行,而不是一一追加。为什么我的表格没有正确填充?
【问题讨论】:
-
嗨,将 $(
#body_deets > tr) 更改为 $(#body_deets > tr:last) 看看会发生什么。 -
@Swati,工作!如果您将其添加为答案,我可以检查它。谢谢!
标签: javascript jquery arrays object ecmascript-6