M trying to create datatable out of uploaded csv file. the only problem i'm facing is defining table column header. Currently i have done it like this, defining header manually.
var table = $('#example').DataTable({
    columns: [{
          "title": "Number",
          "data": "Number"
      }, {
          "title": "Category",
          "data": "Category"
      }, {
          "title": "Assignment group",
          "data": "Assignment group"
      }
      ]
});
and passing csv data through Jquery CSV
 var f = event.target.files[0];
if (f) {
    var r = new FileReader();
    r.onload = function(e) {
        console.log("on load function");
        var result = $.csv.toArrays(e.target.result);
        table.rows.add($.csv.toObjects(e.target.result)).draw();
    }
    r.readAsText(f);
} else {
    alert("Failed to load file");
}
this is working fine. I want to define the column header directly from csv file itself.
Tried
 var f = event.target.files[0];
if (f) {
    var r = new FileReader();
    r.onload = function(e) {
        console.log("on load function");
        var result = $.csv.toArrays(e.target.result); // This will give CSV rows
        var csvHeader = result[0]; // This will give first CSV header
        var option;
        $.each( csvHeader, function( value ){
           console.log(value)
           // Now iterate each value to define Datatable column
           option = // Define column  which will create below column definition 
           /* columns: [{
                         "title": "Number",
                         "data": "Number"
                     }, {
                         "title": "Category",
                         "data": "Category"
                     }, {
                         "title": "Assignment group",
                         "data": "Assignment group"
                     }, {
                          "title": "Short description",
                          "data": "Short description"
                      },
                      {
                          "title": "Description",
                          "data": "Description"
                      }
                     ]*/
        });
        var table = $('#example').DataTable({
          //Define datatable passing column definition as option 
        });
        table.rows.add($.csv.toObjects(e.target.result)).draw();
    }
    r.readAsText(f);
} else {
    alert("Failed to load file");
}
Thanks in advance.
                        
Any reason for using
FileReaderinstead of$.getor similar?FileReaderis not supported by all browsers, like IE9 and Opera mini.Anyway - since you read a CSV file, and end up with arrays of strings ready to be added to the table, there is no need for defining
dataproperties incolumns. In fact it only takes a few very simple steps to generate a dataTable showing a CSV using$.csv. The below code takes any well formed CSV and publish it as a dataTable :