datatables - How to display the column headers dynamically in jquery data table -
i have below code displaying array of objects having property , value in data table. here column headers hardcoded seen in below html code. how can make dynamic based on input dataset?
var dataset = [{ "latitude": 18.00, "longitude": 23.00, "name": "pune" }, { "latitude": 14.00, "longitude": 24.00, "name": "mumbai" }, { "latitude": 34.004654, "longitude": -4.005465, "name": "delhi" },{ "latitude": 23.004564, "longitude": 23.007897, "name": "jaipur" }]; $(document).ready(function() { $('#example').datatable( { data: dataset, "columns": [ { "data": "name" ,"title":"custom name"}, { "data": "latitude" }, { "data": "longitude" }, ] } ); } ); <table id="example" class="display" cellspacing="0" width="100%"> <thead> <tr> <th>name</th> <th>latitude</th> <th>longitude</th> </tr> </thead> </table>
assuming structure of objects in dataset not change, use first object build json object external datatable declaration. if objects not of consistent structure, can tweak logic inside $.each structure handle that.
here's quick hack:
var dataset = [{ "latitude": 18.00, "longitude": 23.00, "name": "pune" }, { "latitude": 14.00, "longitude": 24.00, "name": "mumbai" }, { "latitude": 34.004654, "longitude": -4.005465, "name": "delhi" }, { "latitude": 23.004564, "longitude": 23.007897, "name": "jaipur" }]; var my_columns = []; $.each( dataset[0], function( key, value ) { var my_item = {}; my_item.data = key; my_item.title = key; my_columns.push(my_item); }); $(document).ready(function() { $('#example').datatable({ data: dataset, "columns": my_columns }); });
you should consider removing static table content in html this
<table id="example" class="display" cellspacing="0" width="100%"></table>
here's jsfiddle https://jsfiddle.net/z4t1po8o/18/
have fun.
Comments
Post a Comment