[SalesForce] LWC – Iterate through rows of lightning datatable using javascript

Are we able to iterate through the rows of a lighting datatable and query each columns value in Javascript?

Like this, but for a lightning datatable: https://stackoverflow.com/questions/3065342/how-do-i-iterate-through-table-rows-and-cells-in-javascript

I would imagine it's something like below, but this doesn't work obviously.

var rows = this.template.querySelector('my-custom-datatable');
for (var i = 0, row; row = table.rows[i]; i++) {
   //iterate through rows
   //rows would be accessed using the "row" variable assigned in the for loop
   for (var j = 0, col; col = row.cells[j]; j++) {
     //iterate through columns
     //columns would be accessed using the "col" variable assigned in the for loop
   }  
}

Best Answer

Another way would be to get the lightning-datatable using template.querySelector and then access the rows attribute

 iterateOverTable(event){        
        var table = this.template.querySelector('lightning-datatable');
        var rows = table.data;
        rows.forEach(function(element){
            console.log(element.name);
        });

    }

Playground Link : https://developer.salesforce.com/docs/component-library/tools/playground/Nh9CElBEE/1/edit

Related Topic