使用Javascript将2D数组转换为HTML表格
P粉009828788
P粉009828788 2023-08-13 17:05:44
0
1
529
<p>我在我的Javascript中有一个二维数组。该数组被赋予变量'arr',并且看起来像这样:</p> <pre class="brush:php;toolbar:false;">[ [ "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", }, ], ]</pre> <p>我想在屏幕上给用户一个整洁的HTML表格,键作为表头,值作为行,如下:</p> <table class="s-table"> <thead> <tr> <th>cat_id</th> <th>cat_name</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Tiger</td> </tr> <tr> <td>2</td> <td>Lion</td> </tr> <tr> <td>3</td> <td>Cheetah</td> </tr> <tr> <td>4</td> <td>Leopard</td> </tr> </tbody> </table> <p>我已经查看了很多关于StackOverflow和网络上的文章,但我不是一个Javascript专家,老实说,我无法让任何东西工作。非常感谢任何帮助!</p> <p>我的HTML中包含了空表格代码:</p> <p><br />></p> <pre class="snippet-code-js lang-js Prettyprint-override"><code>const arr = [["0", { cat_id: "1", cat_name: "Tiger", },], ["1", { cat_id: "2", cat_name: "狮子", },], ["2", { cat_id: "3", cat_name: "猎豹", },], ["3", { cat_id: "5", cat_name: "豹子", },],] var tableBody = document.getElementById("wrap"); tableBody.innerHTML = ""; arr.forEach(函数(行){ var newRow = document.createElement("tr"); tableBody.appendChild(newRow); if (数组的行实例) { row.forEach(函数(单元格){ var newCell = document.createElement("td"); newCell.textContent = 单元格; newRow.appendChild(newCell); }); } 别的 { newCell = document.createElement("td"); newCell.textContent = 行; newRow.appendChild(newCell); } });</code></pre> <pre class="snippet-code-html lang-html Prettyprint-override"><code><table id="wrap"></table></code></pre> <p><br />></p> <p>因为arr是一个二维阵列,所以我的代码目前仅产生以下表格:</p>
0 [对象对象]
1 [对象对象]
2 [对象对象]
3 [对象对象]
<p>我明白<em>为什么</em>会发生这种情况,但我的 JS 能力足以实现我想要的结果。</p>
P粉009828788
P粉009828788

全部回复(1)
P粉226413256

这是一个示例,它迭代每个嵌套数据对象的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);
  }
}
<table id="wrap"></table>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!