我在我的Javascript中有一个二维数组。该数组被赋予变量'arr',并且看起来像这样:
[
[
"0",
{
cat_id: "1",
cat_name: "Tiger",
},
],
[
"1",
{
cat_id: "2",
cat_name: "Lion",
},
],
[
"2",
{
cat_id: "3",
cat_name: "Cheetah",
},
],
[
"3",
{
cat_id: "5",
cat_name: "Leopard",
},
],
]
我想在屏幕上给用户一个整洁的HTML表格,键作为表头,值作为行,如下:
| cat_id | cat_name |
|---|---|
| 1 | Tiger |
| 2 | Lion |
| 3 | Cheetah |
| 4 | Leopard |
我已经查看了很多关于StackOverflow和网络上的文章,但我不是一个Javascript专家,老实说,我无法让任何东西工作。非常感谢任何帮助!
我的HTML中包含了空表格代码:
const arr = [["0", { cat_id: "1", cat_name: "Tiger", },], ["1", { cat_id: "2", cat_name: "Lion", },], ["2", { cat_id: "3", cat_name: "Cheetah", },], ["3", { cat_id: "5", cat_name: "Leopard", },],]
var tableBody = document.getElementById("wrap");
tableBody.innerHTML = "";
arr.forEach(function (row) {
var newRow = document.createElement("tr");
tableBody.appendChild(newRow);
if (row instanceof Array) {
row.forEach(function (cell) {
var newCell = document.createElement("td");
newCell.textContent = cell;
newRow.appendChild(newCell);
});
} else {
newCell = document.createElement("td");
newCell.textContent = row;
newRow.appendChild(newCell);
}
});
<table id="wrap"></table>
因为arr是一个二维数组,所以我的代码目前只会产生以下表格:
0 [object Object] 1 [object Object] 2 [object Object] 3 [object Object]
我明白为什么会发生这种情况,但我的JS水平不足以实现我想要的结果。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
这是一个示例,它迭代每个嵌套数据对象的
Object.entries,首先从键构建标题行,然后从值构建数据行。const arr = [ ["0", { cat_id: "1", cat_name: "Tiger" }], ["1", { cat_id: "2", cat_name: "Lion" }], ["2", { cat_id: "3", cat_name: "Cheetah" }], ["3", { cat_id: "5", cat_name: "Leopard" }], ]; var tableBody = document.getElementById("wrap"); tableBody.innerHTML = ""; const data = arr.map(a => Object.entries(a[1]).sort(([a], [b]) => a.localeCompare(b)) ); const headerRow = document.createElement("tr"); tableBody.appendChild(headerRow); for (const [key] of data[0]) { const newCell = document.createElement("td"); newCell.textContent = key; headerRow.appendChild(newCell); } for (const datum of data) { const newRow = document.createElement("tr"); tableBody.appendChild(newRow); for (const [, value] of datum) { const newCell = document.createElement("td"); newCell.textContent = value; newRow.appendChild(newCell); } }