Last active
May 18, 2017 20:05
-
-
Save smartameer/fe3b13f6252252e32fd9 to your computer and use it in GitHub Desktop.
Generate Table from JSON Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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 = $('<table>'), | |
tableHead = $('<thead>'), | |
tableBody = $('<tbody>'), | |
tblHeaderRow = $('<tr>'); | |
$.each(data, function (index, value) { | |
var tableRow = $('<tr>').addClass(index%2 === 0 ? 'even' : 'odd'); | |
$.each(value, function (key, val) { | |
if (index == 0 && $.inArray(key, hidecolumns) <= -1 ) { | |
var theaddata = $('<th>').text(key); | |
tblHeaderRow.append(theaddata); | |
} | |
if ($.inArray(key, hidecolumns) <= -1 ) { | |
var tbodydata = $('<td>').text(val); | |
tableRow.append(tbodydata); | |
} | |
}); | |
$(tableBody).append(tableRow); | |
}); | |
$(tblHeaderRow).appendTo(tableHead); | |
tableHead.appendTo(table); | |
tableBody.appendTo(table); | |
$(this).append(table); | |
return this; | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment