P粉2264132562023-08-14 09:39:26
Here is an example that iterates over the Object.entries
of each nested data object, first building the header row from the keys and then the data rows from the values.
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>