Convert JSON array to an HTML table in jQuery

前端 未结 15 1144
温柔的废话
温柔的废话 2020-11-22 16:33

Is there a really easy way I can take an array of JSON objects and turn it into an HTML table, excluding a few fields? Or am I going to have to do this manually?

15条回答
  •  半阙折子戏
    2020-11-22 17:03

    Modified a bit code of @Dr.sai 's code. Hope this will be useful.

    (function ($) {
        /**
         * data - array of record
         * hidecolumns, array of fields to hide
         * usage : $("selector").generateTable(json, ['field1', 'field5']);
         */
        'use strict';
        $.fn.generateTable = function (data, hidecolumns) {
            if ($.isArray(data) === false) {
                console.log('Invalid Data');
                return;
            }
            var container = $(this),
                table = $(''),
                tableHead = $(''),       
                tableBody = $(''),       
                tblHeaderRow = $('');       
    
            $.each(data, function (index, value) {
                var tableRow = $('').addClass(index%2 === 0 ? 'even' : 'odd');      
                $.each(value, function (key, val) {
                    if (index == 0 && $.inArray(key, hidecolumns) <= -1 ) { 
                        var theaddata = $('
    ').text(key); tblHeaderRow.append(theaddata); } if ($.inArray(key, hidecolumns) <= -1 ) { var tbodydata = $('').text(val); tableRow.append(tbodydata); } }); $(tableBody).append(tableRow); }); $(tblHeaderRow).appendTo(tableHead); tableHead.appendTo(table); tableBody.appendTo(table); $(this).append(table); return this; }; })(jQuery);

    Hoping this will be helpful to hide some columns too. Link to file

    提交回复
    热议问题