动态树数据结构和HTML表格

问题描述 投票:0回答:1

我正在尝试使用 TypeScript 和 HTML 编写代码来创建一个表格来显示我的数据。然而,由于管理“rowspan”的复杂性,我遇到了困难。这是我的数据:

data = [
    { d: 1, A: [{ a: 11, C: [{ c: 111 }, { c: 112 }] }, { a: 12, C: [] }] },
    { d: 2, A: [{ a: 21, C: [{ c: 211 }] }] }
]

在此输入图像描述 让它变得更加困难的是我希望它是动态的。这是要检查的其他数据:

data = [
    { d: 1, A: [{ a: 11, C: [{ c: 111 }, { c: 222 }] }, { a: 22, C: [{ c: 333 }, { c: 444 }] }] },
    { d: 2, A: [{ a: 33, C: [{ c: 555 }] }] },
    { d: 3, A: [{ a: 44, C: [{ c: 666 }, { c: 777 }, { c: 888 }] }, { a: 55, C: [{ c: 999 }] }] }
]

我尝试了多个代码,但没有任何效果。

html typescript data-structures html-table frontend
1个回答
0
投票

这是一个 JavaScript 函数,可以从该层次结构创建一个表:

function createTable(hierarchy) {
    const table = document.createElement("table");
    table.insertRow(); // header row
    return hierarchy.reduce((table, obj) => {
        // Extract information from object
        let data, arr, colName;
        for (const [key, val] of Object.entries(obj)) {
            if (Array.isArray(val)) {
                arr = val;
            } else {
                colName = key;
                data = val;
            }
        }
        // Create a table from the object
        let nextTable;
        if (arr?.length) { // If there is nested information: recur
            nextTable = createTable(arr);
        } else {
            nextTable = document.createElement("table");
            nextTable.insertRow(); // heading
            nextTable.insertRow(); // data
        }
        nextTable.rows[0].insertCell(0).textContent = colName;
        const cell = nextTable.rows[1].insertCell(0);
        cell.textContent = data;
        if (nextTable.rows.length > 2) {
            cell.setAttribute("rowspan", nextTable.rows.length - 1);
        }
        // Merge nextTable into table:
        const tbody = table.children[0];
        while (nextTable.rows.length > 1) {
            tbody.appendChild(nextTable.rows[1]);
        }
        if (nextTable.rows[0].cells.length > table.rows[0].cells.length) {
            table.rows[0].remove();
            tbody.insertBefore(nextTable.rows[0], table.rows[0]);
        }
        return table;
    }, table);
}

// Demo with your example data:
const data = [
    { d: 1, A: [{ a: 11, C: [{ c: 111 }, { c: 112 }] }, { a: 12, C: [] }] },
    { d: 2, A: [{ a: 21, C: [{ c: 211 }] }] }
];
// Create the table HTML Element
const table = createTable(data);
// Add it to the current document:
document.querySelector("#container").appendChild(table);
table { border-collapse: collapse; }
td, table { border: 1px solid; vertical-align: top; text-align: center; min-width: 50px; }
<div id="container"></div>

© www.soinside.com 2019 - 2024. All rights reserved.