Convert Object to HTML table in JavaScript

June 26, 2020

HTML table

A sample HTML Table code

<table>
    <thead>
        <th colspan='3'>Numbers</th>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>2</td>
        </tr>
        <tr>
            <td>1</td>
            <td>2</td>
            <td>3</td>
        </tr>
    </tbody>
</table>

The above html table code can be represented by JavaScript object as

let headerRow = [{colspan:3, text : "Numbers"}];
let row1 = [{text:"1" },{text:"2",colspan:2 }];
let row2 = [{text:"3" },{text:"4" }, {text:"5" }];

let tableObj = {
    head : headerRow, // header can only have one row
    body : [ {row: row1},{ row: row2} ]
}

Let's write the function to turn the object into html table

const LINE_SEPARATOR = "\n" ;

Let's write a function which will form the head part

/*
tableObj contains head key , which has array of header column name
*/
function generateRow(row, isHeader) {
    let TAG_NAME = isHeader ? "th" : "td";
    let rowString = "<tr>" + LINE_SEPARATOR;
    for(let i = 0, len = row.length; i < len; i++){
        let  {colspan, text} = row[i];
        // i am only adding col span attribute but you can add rowspan, and other property
        rowString += `<${TAG_NAME} colspan=${colspan||1}> ${text} </${TAG_NAME}>` + LINE_SEPARATOR;
    }
    rowString += "</tr>"
    return rowString;
}

function generateHeader(tableObj){
    let headTagString = "";
    let headObj = tableObj.head;
    if(headObj && headObj.length) {
        headTagString += "<thead>" + LINE_SEPARATOR; // open header

        headTagString += generateRow(headObj, true); // get row String

        headTagString +=LINE_SEPARATOR + "</thead>" + LINE_SEPARATOR; // close header
    }
    return headTagString;
}

Let's write a function to which will form the table body, here the table body data available in body property which is an array which have row data object

function generateBody(tableObj){
    let bodyTagString = "";
    let bodyObj = tableObj.body;
    if(bodyObj && bodyObj.length){
        bodyTagString += "<tbody>" + LINE_SEPARATOR;
        for(let i = 0, rowLen = bodyObj.length; i < rowLen; i++ ){
            let rowData = bodyObj[i];
            bodyTagString += generateRow(rowData.row, false);
        }
        bodyTagString += LINE_SEPARATOR + "</tbody>" + LINE_SEPARATOR;
    }
    return bodyTagString;
}

Let's call the function

let headerRow = [{colspan:3, text : "Numbers"}];
let row1 = [{text:"1" },{text:"2",colspan:2 }];
let row2 = [{text:"3" },{text:"4" }, {text:"5" }];

let tableObj = {
    head : headerRow, // header can only have one row
    body : [ {row: row1},{ row: row2} ]
}
let tableStr = "<table>";
tableStr += generateHeader(tableObj);
tableStr += generateBody(tableObj);
// you can add code for footer
tableStr += "</table>"

The above code is just a beginning, you can develop more from here to generate complex table . Hope it gives you some idea for your project. Thanks