Create HTML table from JavaScript object

前端 未结 8 1149
后悔当初
后悔当初 2020-12-05 12:02

I am a beginner of JavaScript and want to display an array of objects in HTML.

The format of the data is like this:

[
  {\"key\":\"apple\",\"value\":         


        
8条回答
  •  难免孤独
    2020-12-05 12:32

    Here a function for build a table from any collection (array of objects)

    Table creator

    const data=[
        {
            name: "Kapil",
            age:  21,
            status: "Active"
        },
        {
            name: "John",
            age:  28,
            status: "Inactive"
        },
        {
            name: "Deos",
            age:  18,
            status: "Active",
            testing: 'Gooo!!'
        }
    ]
    
    const createTable=function(data){
    const table = document.createElement("table");
    const header = document.createElement("tr");
    const keys=Object.keys(data[0])
    console.log(keys)
    for(const key of keys){
        const th=document.createElement("th");
        th.appendChild(document.createTextNode(key));
        header.appendChild(th);
    }
    table.appendChild(header);
    const len=data.length
    for(const row of data) {
        const tr = document.createElement("tr");
        for(const key of keys){
            const td = document.createElement("td");
            const content=row[key] ||''
            td.appendChild(document.createTextNode(content));
            tr.appendChild(td);
            delete row[key]
        }
      /****
      you can omit next cycle if all object have the same structor or if the first element of collection have all fields
      ****/
        for(const key in  row){
            const th=document.createElement("th");
            th.appendChild(document.createTextNode(key))
            keys.push(key)
            header.appendChild(th);
            const td = document.createElement("td");
            const content=row[key] ||''
            td.appendChild(document.createTextNode(content));
            tr.appendChild(td);
        }
        table.appendChild(tr);
    }
    return table
    

    }

提交回复
热议问题