clde clde - 2 months ago 13
Javascript Question

DataTables: Creating column properties dynamically through a loop

I have succesfully implemented the DataTables (version 1.10+) plugin, where I am using the following code snippet to define the columns:

"columns": [
{"width" : "25%", "orderSequence": [ "desc", "asc" ]},
{"width" : "25%", "orderSequence": [ "desc", "asc" ]},
{"width" : "25%", "orderSequence": [ "desc", "asc" ]},
{"width" : "25%", "orderSequence": [ "desc", "asc" ]}
],


My problem is now that I always have to define these properties for the amount of columns I am using in my table. Here, I have 4 columns and therefore there are 4 properties. Since I want to use my code for multiple tables, BUT with different amounts of columns, I would like to have this block of code created dynamically through a loop on the basis of the column amount.

Is this in general possible, and does anybody may have a solution? Any help is appreciated!!

Ted Ted
Answer
function DataTableRowsDefs(columnCount)
{
   // create the object and the 1st row
   var cols = "columns" : [{"width" : "25%", "orderSequence": [ "desc", "asc" ]}];

   // repeat for every element after that
   for (i = 1; i < columnCount; i++) { 
      cols.columns.push({"width" : "25%", "orderSequence": [ "desc", "asc" ]});
   }

   // return array
   return cols;  
}

// call function:
DataTableRowsDefs(4);

EDIT

Corrected redundancy

function DataTableRowsDefs(columnCount) {

  // create a single column
  var column = {
    "width": "25%",
    "orderSequence": ["desc", "asc"]
  };

  // create the object and add the 1st column
  var jsonColumns = {
    "columns": [column]
  };

  // repeat for every column after that
  for (i = 1; i < columnCount; i++) {
    jsonColumns.columns.push(column);
  }

  // return array
  return(jsonColumns);
}

// call function:
DataTableRowsDefs(4);