How to display the column headers dynamically in jquery data table

后端 未结 2 2058
别那么骄傲
别那么骄傲 2021-01-06 06:14

I have the below code for displaying array of objects having property and a value in a data table. But here the column headers are hardcoded as seen in my below html code. H

2条回答
  •  死守一世寂寞
    2021-01-06 07:08

    Assuming the structure of the objects in the dataSet does not change, you could use the first object to build the json object external to the DataTable declaration. If the objects are not of a consistent structure, then you can tweak the logic inside the $.each structure to handle that.

    Here's a 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 also consider removing all the static table content in your HTML like this

    Here's the jsFiddle https://jsfiddle.net/z4t1po8o/18/

    Have fun.

提交回复
热议问题