javascript - 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);
}
}
解决方案
这两行有效:
// 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);
}
推荐阅读
- javascript - 在 React 中测试 DOM 更新
- firebase - Flutter:识别firebase集合中是否有文档
- python - 如何修复“import crccheck”上的 Pylint 导入错误?
- python - 按日期和总和列分组
- ffmpeg - MXE 编译,openjpeg.h not found 错误
- python - 如何将此代码转换为功能工作代码?
- sql - NOT EXISTS 查询与 REPLACE 永远运行
- apache-kafka - 无法在kafka connect中使用接收器连接器
- google-sheets - 如何根据往年数据计算 Google 表格中的概率
- php - 如何在 php 代码中设置 MAILER_DSN 参数?