Datatables use column names in render

24 views Asked by At

How can I use column names to get data in a render function, rather than the index?

tableCols: [
  { title:'ID',     name: 'ID' },
  { title:'Active', name: 'Active',

    render(data,type,row,meta){
      return row[0] > 3  // NO
      return row.ID > 3  // YES
    }

  }
],


created_row: function(row,data,index){
  $(row).css('background-color', row[1] ? 'green' : 'red')      // NO
  $(row).css('background-color', row.Active ? 'green' : 'red')  // YES
}
1

There are 1 answers

0
Travis Heeter On

I was able to figure this out through experimentation with orthogonal data. And a few other sources.

The key is how your data is formatted when it's attached to the data table.

Datatables accepts at least two types of data:

a 2-D Array

[["value1","value2","value3"]]

an array of objects

[{"key1":"value1","key2":"value2","key3","value3"}]

If you use the latter you will be able to use the keys instead of indexes. If you use the former, you will only have access to indexes.

So, for my example...

tableData: [
  {"ID":1},
  {"ID":2},
  {"ID":3},
  {"ID":4},
],
tableCols: [
  { title:'ID',     name:'ID', data:'ID' },
  { title:'Active', name:'Active',

    render(data,type,row,meta){
      return row.ID > 3  
    }

  }
],


created_row: function(row,data,index){
  $(row).css('background-color', row.Active ? 'green' : 'red')
}

Another thing to note: There does not seem to be a way to switch back and forth between indexes and names without a lot of work, so be sure this is what you want before you change how your data is displayed.