Jordi Z
Jordi Z

Reputation: 179

Make DataTables column variable based on an array

Background:
I'm busy building a application which (amongst other things) has to be able to show a report. I choose DataTables because it works awesomely and it was easy to implement. I've made an application which is based on one (static) dataset. However, I have gotten the request to alter the application to be able to work with multiple datasets.

Question:
Amonst other things, i want to replace the statically defined columns (see code snippet), with a variable. In this case an array with id, keten, name, x, y, which will be declared somewhere else dynamically.

How do i change my function to incorporate a variable array instead of hardcoding the columns?

The end result should change from

"columns": [
    {"data": "id"},
    {"data": "keten"},
.......

to something like

"columns": [
    {"data": *variableReportData*}

Code:

function rapport_vullen(){
    $("#rapport").dataTable({
        destroy: true,
      "aaData": geojson.features.map(function(row) { return row.properties; }),
        "columns": [
            {"data": "id"},
            {"data": "keten"},
            {"data": "name"},
            {"data": "x"},
            {"data": "y"}
        ]
    });
    download_rapport()
};

Upvotes: 0

Views: 1047

Answers (2)

Rohìt Jíndal
Rohìt Jíndal

Reputation: 27222

You can use javascript .map() function :

it will convert the array elements into the objects as you wanted.

var arr = [id, keten, name, x, y];

var objArr = arr.map(function(item) { return {data:item} });

console.log(objArr);

 [{"data": "id"},
  {"data": "keten"},
  {"data": "name"},
  {"data": "x"},
  {"data": "y"}]

Then, you can directly use this in your datatable function. Thanks

Upvotes: 1

castletheperson
castletheperson

Reputation: 33496

You can convert the array of column names into an array of objects by using .map() like so:

var inputArray = ["a","b","c"]; // for example
inputArray.map(function(d) { return {data:d}; });

So the I/O would be:

["a","b","c"] --> [{data:"a"},{data:"b"},{data:"c"}]

And then create the DataTable using the output.

function rapport_vullen(inputArray){
    $("#rapport").dataTable({
        destroy: true,
        aaData: geojson.features.map(function(row) { return row.properties; }),
        columns: inputArray.map(function(d) { return {data:d}; })
    });
    download_rapport()
}

Upvotes: 1

Related Questions