Access table data by column name (not index number) in filter
Access table data by column name (not index number) in filter
Ronan
Posts: 7Questions: 3Answers: 0
Hello,
I am happily using datatables and I added filters which work well:
//filtering function
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex )
{
//Price range
var price_min = $('#price_min').val() * 1;
var price_max = $('#price_max').val() * 1;
var price = parseFloat( data[7] ) || 0; // price column
if ( ( price_min != '' && price < price_min ) || ( price_max != '' && price > price_max ) )
return false;
return true;
}
);
=> I would like to improve the code by accessing data by column name ( e.g. : data['prix'] ) rather than index number ( data[7] )
Thank you in advance for your help !
This question has an accepted answers - jump to answer
This discussion has been closed.
Answers
Unless I'm mis-understanding what you're looking for, you can do that by initializing the columns to have names / titles and then doing a query on that since Javascript doesn't care if it's a number or a word. I'm using names of columns to fetch data, but the way I do it is overly complicated and unique to try and explain how I end up doing it but that's my best guess as to where to start.
@Rpiechura, thank you for your answer.
I am already initializing the table by giving names to each column :
But I don't see how I can access the data by column name/title.
The function triggered by the filter extension (see 1st post) has a 'data' parameter which seems to be a numeric indexed only (this is what I got from javascript console) :
The 'settings' object contains lot of data, but I couldn't find a way to easily access data by column name. Am I missing something obvious ?
I am open to suggestion, even if the way to go is complex.
(if you are using 1.10). Maybe....
data[oTable.column('prix:name').index()]
or in a separate function
function getColumnNumberByName(name) {
return oTable.column(name + ":name").index();
}
data[getColumnNumberByName('prix')]
Feels a bit verbose, but it should work.
Hello @sigriedlk,
I will try that immediately then post feedback.
That looks good, thank you !
Hello again @sigriedlk,
It does work with oTable.column('prix:name').index() even though it requires to add a "name" definition to each column.
This would allow me to have a more robust code, specifically in case of change in the column order.
BUT I have the feeling that it slowed down execution by a lot. I will run some performance test and post feedback again.
I finally confirm that oTable.column('prix:name').index() works but very slowly. Running it 1000 times takes up to 10 seconds, which are pure overhead.
I used this syntax to build a global static array of column order, which I use in the filter functions.
and :
=> That way, I get both an evolutive and efficient code (even though I had preferred avoiding global data).