首页 > 解决方案 > Javascript:将数据从数组导出到 HTML 表

问题描述

我有一个二维字符串数组,例如:

[["Application1", "11106.exampleserver.com", "11109.exampleserver.com", "11102.exampleserver.com", "11105.exampleserver.com" "Database, AFPUOR(KNAJKLD)", "Database, UOQZRNJ(LKUJD)" ],
 ["Application2", "44407.exampleserver.com", "11106.exampleserver.com", "11104.exampleserver.com", "Database, POJPR (OIUOLWA) ", "Database, UIAHSD (JJJQEP)" ],...]

等等..(每次不同数量的服务器/数据库)

如何按数据库/服务器对“应用程序”进行排序并显示/保存这些数据库/服务器?管理阵列的最佳方式是什么?

我需要一个 HTML 表:在表头中是应用程序的名称,然后是服务器和数据库(我需要划分服务器和数据库)。

现在我可以使用以下代码输出数据库:

for(j=0; j < columns.length; j++){
    for(i=0;i < columns[j].length; i++){
        var db = columns[j][i].match("Database")
        if (db != null){
            console.log("APP: " +  j + ": " + columns[j][0] + " , ID: " + i + ": " + db.input)
            //outpus e.g.: APP: 0: Application1, ID: 5: Database XYZ
        }
    }
}

和具有此代码的服务器:

for(j=0; j < columns.length; j++){
    for(i=1;i < columns[j].length; i++){
        var db = columns[j][i].match("Database")
        if (db == null){
            console.log("APP: " +  j + ": " + columns[j][0] + " , ID: " + i + ": " + columns[j][i])
            //outpus e.g.: APP: 0: Application1, ID: 1: Server1.1
        }
    }
}

标签: javascriptarraysjsonhtml-table

解决方案


试试这个,

在你的 html

<table >
        <thead>
            <tr>
                <th>Application</th>
                <th>ID</th>
                <th>Database</th>
                <th>Server</th>
            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>

在你的 javascript

const table = document.getElementsByTagName('tbody')[0];

data.forEach((entity,index) => {

    let rowData = {}

    rowData.applicationName = entity[0]
    rowData.id = index
    rowData.databases = []
    rowData.servers = []

    entity.forEach(value => {

        if (value.match('Database')){
            rowData.databases.push(value)        
        }else{
            rowData.servers.push(value)   
        }

    })

    appendRow(rowData)
})


function appendRow(rowData) {

    table.innerHTML +=  `<tr>
        <td>${rowData.applicationName}</td>
        <td>${rowData.id}</td>
        <td>${rowData.databases.join(',')}</td>
        <td>${rowData.servers.join(',')}</td>    
    </tr>`

}

希望这可以帮助!


推荐阅读