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>