0

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 
    } ); 

2 Answers 2

3

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
});
Sign up to request clarification or add additional context in comments.

Comments

1

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
}); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.