Skip to content

Javascript Create Html Table Based On Key Value Array

No idea why there wasn’t a quick and simple solution out there for me to use, so I just went ahead to create my own. Basically, the use case for this is when you retrieve data from your database, and you have a set of data where all the keys are the same. Using this function, you can easily create a html table (with valid <thead> and <tbody>tags) that you can use in your code. Having <thead> and <tbody> tags also means that its DataTables compatible !
function createTable(array) {
    if( array.length <= 0 ) 
        return null;
        
    var table = document.createElement('table');
    var keys = Object.keys(array[0]);
    
    var thead = document.createElement("thead");
    var header_row = document.createElement('tr');
    for(var i = 0;i < keys.length;i ++)
    {
        var header_cell = document.createElement('th');
        header_cell.textContent = keys[i];
        header_row.appendChild(header_cell);
    }
    thead.appendChild(header_row);
    table.appendChild(thead); // append thead to table
    
    var tbody = document.createElement("tbody");
    for (var i = 0; i < array.length; i++) {
        var row = document.createElement('tr');
        for (const [key, value] of Object.entries(array[i])) {
            var cell = document.createElement('td');
            console.log("key : " + key);

            cell.textContent = value;
            row.appendChild(cell);
        }
        tbody.appendChild(row);
    }
    table.appendChild(tbody); // append tbody to table
    
    return table;
}
Call the function above, and you will get a <table> element with all your data converted into rows. You can will then need to append your data somewhere, such as
document.body.appendChild(table);
You are good to go !
Enjoyed the content ? Share it with your friends !
Published inDevelopmentProgramming

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *