henri_1310
henri_1310

Reputation: 315

Dynamic columns with Datatables javascript

js in order to display a json file. I extract the name of my columns and build an array like this one :

columns = ["Date", "C2R", "CM", "Total"]

My sTitle and mData have the same name so I try to do that but fail.

    jQuery('#result_example').dataTable( {
        "data": result_table,
        "columns": [
            jQuery.each(columns, function(i, value){
                //console.log(value); which give ["Date", "C2R", "CM", "Total"]
                { "sTitle": + value + , "mData": + value + },  
            })
        ],

        paging: true,
        searching: false,
        "bInfo" : false 
    } ); 

The objective is to have a result like this :

    jQuery('#result_example').dataTable( {
        "data": result_table,
        "columns": [
                { "sTitle": "Date" , "mData": "Date" },
                { "sTitle": "C2R" , "mData": "C2R" },
                { "sTitle": "CM" , "mData": "CM" },
                { "sTitle": "Total" , "mData": "Total" }
        ],

        paging: true,
        searching: false,
        "bInfo" : false 
    } ); 

Upvotes: 0

Views: 2292

Answers (2)

Jai
Jai

Reputation: 74738

Issue:

When you execute your datatable code it does not get the columns name because you are extracting it later but at that moment datatable code has been executed, so what you can do is this with jQuery.map() is to create an array filled with objects of each iteration of your columns array:

var colData = $.map(columns, function(colName) { // creates an array
   return { "sTitle": colName, "mData": colName};// fills with js objects
}); 

jQuery('#result_example').dataTable( {
     "data": result_table,
     "columns":colData, //<---------you can pass it here.
     // other code as is
}); 

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59232

You can build an object outside and then use it inside dataTable

var clmns = [];
jQuery.each(columns, function(i, value) {
    clmns.push({ "sTitle": value, "mData": value}); // push it in
});    
jQuery('#result_example').dataTable({
    "data": result_table,
    "columns": clmns, // use it here
    paging: true,
    searching: false,
    "bInfo": false
});

Upvotes: 3

Related Questions