Dynamically set datasource for jquery datatable columns

Question

Is there a way we can dynamically set data source of datatable columns? Like I set columns.data by hardcoding each property name like this:

$.ajax({
    data: JSON.stringify(data),
    url: urlGetProviderQualificationTimeData,
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    success: function (obj) {
        if (obj.success) {
            $('#tblProds').dataTable({
            data: obj.data.ProdsDetails,
            columns: [
                { "data": "PName" },
                { "data": "PTime" }  //hardcoded mapping of properties     
            ]
            });
        }
    },
});

ProdsDetails sample array:

Array[2]
0:Object
    PName:"ATT",
    PTime:"6.48"   
1:Object
    PName:"CENTURYLINK",
    PTime:"3.67"

Is there a way we can get rid of this hardcoded mapping of properties and columns?


Show source
| jquery   | json   | datatables   2017-01-02 10:01 2 Answers

Answers ( 2 )

  1. 2017-01-02 10:01

    I had the same problem and worked around this by creating an extra json array for the columns.data property. Is used a php function to loop through the headers and put it into a json array.

  2. 2017-01-02 11:01

    Here is your array :

    var array=[
                 {PName:"ATT",PTime:"6.48" },
                 {PName:"CENTURYLINK",PTime:"3.67"}
              ];
    

    Now, You should get all the keys and build final array:

    var obj=array[0];
    var keys=[];
    for(var k in obj) 
        keys.push({"data":k});
    

    Now, keys array looks like this:

    [
       {"data":"PName"},
       {"data":"PTime"}
    ]
    

    And the last step is to assign array to columns property of DataTable:

    columns:keys
    

    Now this should look like this:

    columns:[
              { "data": "PName" },
              { "data": "PTime" }    
    ]
    

    Hope this helps !.

◀ Go back