How To Repeat The Columns Based On The Json Data For Datatable Display
Hi I have a JSON data coming from AJAX response and it has nested array. [{ 'Solution': 'MobileBroadband', 'Operator': 'MTN', 'VNF': [{ 'vendor': 'vendor1',
Solution 1:
First, you would need to set DataTables ajax
option accordingly:
$('#mytable').DataTable({
ajax: {
...
url: '/getdata'//URL to API that returns your JSON data
}
});
Next, you need to 'flatten' your source JSON structure, so that it contains array of objects where each property corresponds to table column. For that purpose, you may need to use ajax.dataSrc
option (to postprocess received JSON):
$('#mytable').DataTable({
ajax: {
url: '/getdata',
dataSrc: rawJson => rawJson.map(entry => {
entry.VNF.forEach((vnfEntry, vnfEntryIndex) =>Object.entries(vnfEntry).forEach(vnfEntryProp => entry[vnfEntryProp[0] + vnfEntryIndex] = vnfEntryProp[1]));
delete entry.VNF;
return entry;
})
}
});
And finally, you may want to suppress DataTables warning that informs you about missing data for certain columns (as you have different number of NFV vendors for different operators):
$.fn.dataTable.ext.errMode = 'none';
But you must be carefull with that option as it will suppress all error notifications from DataTables engine.
For full-blown demo, you might want to check out this link.
Solution 2:
Try to set your response like this:
var data = [
[ "Row 1 - Field 1", "Row 1 - Field 2", "Row 1 - Field 3" ],
[ "Row 2 - Field 1", "Row 2 - Field 2", "Row 2 - Field 3" ],
];
var columns = [
{ "title":"One" },
{ "title":"Two" },
{ "title":"Three" }
];
$(document).ready(function() {
$('#example').DataTable( {
dom: "Bfrtip",
data: data,
columns: columns
});
});
You can try this in js fiddle
Post a Comment for "How To Repeat The Columns Based On The Json Data For Datatable Display"