首页 > 解决方案 > Javascript ; 从对象数组动态生成的表:如何将键添加为数据单元的类

问题描述

我正在从一组对象构建一个动态表。每行对应一个对象,该行中的每个单元格对应于该对象的一个​​属性的值。所有对象都具有相同的属性列表。

我想要做的是将键作为类添加到生成的表格单元格中,以便添加一个开关来隐藏/显示列以切换增值税。

这是我的数组的样子

let array = [
  {
    category: "Category",
    product: "Product",
    withVAT: "Price including VAT",
    withoutVAT: "Price excluding VAT",
  },
  {
    category: "Rouges",
    product: "Chevigny Vaucluse",
    withVAT: "4,40 €",
    withoutVAT: "3,64 €",
  },
  {
    category: "Rouges",
    product: "Terra Quantum C.Rhône 2018 BIO",
    withVAT: "9,30 €",
    withoutVAT: "7,69 €",
  },
...
]

这是我在 JS 中动态生成的表:

document.onload(generateDynamicTable());

function generateDynamicTable() {
  if (array.length > 0) {
    // Table style
    let table = document.createElement("table");

    // Retrieve column header
    let columns = [];
    for (i = 0; i < array.length; i++) {
      for (key in array[i]) {
        if (columns.indexOf(key) === -1) {
          columns.push(key);
        }
      }
    }

    // TABLE HEAD
    // Create table head
    let tableHead = document.createElement("thead");
    // Create row for table head
    let tableHeadRow = document.createElement("tr");
    // Create cells for table head
    for (i = 0; i < columns.length; i++) {
      let tableHeadCell = document.createElement("th");
      tableHeadCell if (array.length > 0.innerHTML = columns[i];
      tableHeadRow.appendChild(tableHeadCell);
    }

    // TABLE BODY
    // Create table body
    let tableBody = document.createElement("tbody");
    // Create rows for each object in the array
    for (i = 0; i < array.length; i++) {
      let tableRow = document.createElement("tr");
      // Create cells for each row
      for (j = 0; j < columns.length; j++) {
        let tableCell = document.createElement("td");
        tableCell.innerHTML = array[i][columns[j]];
        tableRow.appendChild(tableCell);
      }
      tableBody.appendChild(tableRow);
    }
    table.appendChild(tableBody);

    // Add table to a container
    document.getElementById("dynamicTable").innerHTML = "";
    document.getElementById("dynamicTable").appendChild(table);
  }
}

标签: javascripthtml-tablekey

解决方案


这两行有效:

// create an array with the keys of the properties for the object "array[i]"
let keys = Object.keys(array[i]);
// add the property key to the table cell's classes
tableCell.classList.add(keys[j]);

必须在此处添加它们:

// Create cells for each row
      for (j = 0; j < columns.length; j++) {
        let tableCell = document.createElement("td");
        tableCell.innerHTML = array[i][columns[j]];
        let keys = Object.keys(array[i]);
        tableCell.classList.add(keys[j]);
        tableRow.appendChild(tableCell);
      }


推荐阅读