首頁  >  問答  >  主體

使用Javascript將2D陣列轉換為HTML表格

<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粉009828788P粉009828788405 天前537

全部回覆(1)我來回復

  • P粉226413256

    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>

    回覆
    0
  • 取消回覆