API rows() returns indexes, but I would expect "row" API objects
API rows() returns indexes, but I would expect "row" API objects
dma_k
Posts: 18Questions: 3Answers: 0
Suppose I would like to iterate all rows and apply some logic for each row data:
var matchedRow = null;
myDataTable.rows().each(function(row) {
// Here I would expect that "row" is API object
if (row.data().someField === 10) { // I get "not such method data()" here
matchedRow = row;
... do something ...
return false;
}
});
if (matchedRow) matchedRow.invalidate().draw();
however in given code snippet the variable row
has value something like [11, 8, 5, 4, ...]
, which I would expect to be a result for rows().indexes().each()
call. What I want can be implemented like this (ugly):
var len = myDataTable.rows().indexes().length;
for (var i = 0; i < len; i++) {
var row = myDataTable.row(i);
if (row.data().someField === 10) {
matchedRow = row;
return false;
}
}
How to do it more nicely?
DataTables v1.10.1
This question has an accepted answers - jump to answer
This discussion has been closed.
Answers
You would do something like this:
The selector methods (
rows()
,columns()
,cells()
and their singular counterparts really just build an array of indexes - which you are seeing here.Note also that I've use
eq()
to get the first element of therows()
return only. This is required because the API is multi-table aware - so is looks like a 2D array with the outer array for the tables.Allan
Thanks. I see that it still iterates over the indexes. Would it be nice to add opportunity to iterate rows directly (and perhaps faster then lookup row by index each time)?
Agreed. I'm not sure how much of a performance improvement it would yield (likely only really a few less function calls, since the row index look up is quite fast), but it would certainly help and make the code nicer. I'll look into this. Thanks!
Allan
I wonder if
myDataTable.rows().each(function(row) {...})
construction is possible in recent DataTable versions? And what would be also cool is to enable construction like thismyDataTable.rows().filter(function(row) {...}).invalidate().draw(false);
Thanks.
The
rows().every()
method that was introduced in the recent 1.10.6 release adds this ability :-).For the filter, you can use the
row-selector
as a function which would basically provide that ability.Allan
Dear allan. I have same problem . I can not get data at row selected in DatatTable.
And my script
And then run it , i can not get data in row , It show error "undefined and undefined" . Can you give me some advice . Thank you.
You are accessing the data as an array (
data[1]
), but you are configuring DataTables to use objects...The data is not an array in your situation here, it is an object. Use
data.LOCATION_ID
for example.Allan