Extension method for dynamic table

by Roman Joseph Rimorin

HTML

<div class="main">
</div>

JavaScript

$.fn.buildTable = function buildTable(columns, data) {
    
        //creates table
        var table = $('<table></table>').addClass("table table-striped table-bordered nowrap w-100");

        table.attr("width", "100%");
        table.attr("cellspacing", "0");

        var tr = $('<tr></tr>') //creates row
        var th = $('<th></th>') //creates table header cells
        var td = $('<td></td>') //creates table cells

        var header = tr.clone() //creates header row

        //fills header row
        columns.forEach(function (d) {
            header.append(th.clone().text(d.label))
        })

        //attaches header row
        table.append($('<thead></thead>').append(header))

        //creates empty body
        var tbody = $('<tbody></tbody>')

        //fills out the table body
        if (data)
            $.each(data, function (index, item) {
                var row = tr.clone() //creates a row
                $.each(item, function (key, value) {
                    row.append(td.clone().text(value)) //fills in the row
                })
                tbody.append(row) //puts row on the tbody
            });

        table.append(tbody);
        return table;
    };
    
    var table = $.fn.buildTable([
    	{ "label": "col1" },
      { "label": "col2" },
      { "label": "col3" }
    ],[
    	{ "col1": "test 1.1", "col2": "test 1.2", "col3": "test 1.3"  },
      { "col1": "test 2.1", "col2": "test 2.2", "col3": "test 2.3"  },
      { "col1": "test 3.1", "col2": "test 3.2", "col3": "test 3.3"  },
      { "col1": "test 4.1", "col2": "test 4.2", "col3": "test 4.3"  }
    ]);
    
    $("div.main").html(table);