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?
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
- 热议问题