0 [对象对象] 1 [对象对象] 2 [对象对象] 3 [对象对象]<p>我明白<em>为什么</em>会发生这种情况,但我的 JS 能力足以实现我想要的结果。</p>
P粉2264132562023-08-14 09:39:26
这是一个示例,它迭代每个嵌套数据对象的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>