Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

double forEach to double for Loop

I'm creating an HTML table from a server-side array (google apps script; so tableArray is coming from there). I have two forEach functions which work. However, I'm attempting to use two for loops instead because I'd like to be able to add different classes to different <td>'s.

The output doesn't come out as expected (see #1 below). I can either get an array in one column (instead of each element of the array as a separate <td> or the arrays are repeated in each <td> (see #2 below).

What do I need to change in my for loops to get the expected output?

You can see the version that works HERE.

1 (works with forEach)

enter image description here

2 (does not work with for)

enter image description here

Index.html

function buildTable(tableArray) {
  var table = document.getElementById('table');
  var tableBody = document.createElement('tbody');
  var tbodyID = tableBody.setAttribute('id', 'tbody');

  for (var i = 0; i < tableArray.length; ++i) {
    var column = tableArray[i];
    var colA = column[0];
    var colB = column[1];
    var colC = column[2];
    var colD = column[3];

    if (colA != "") {
      var row = document.createElement('tr');
      for (var j = 0; j < column.length; ++j) {
        var cell = document.createElement('td');
        cell.appendChild(document.createTextNode(column));
        row.appendChild(cell);
      }

    }
    tableBody.appendChild(row);
  }
  table.appendChild(tableBody);
  document.body.appendChild(table);
}
like image 785
N.O.Davis Avatar asked Feb 11 '26 20:02

N.O.Davis


2 Answers

Instead of line cell.appendChild(document.createTextNode(column));

write cell.appendChild(document.createTextNode(column[j]));

You've forgotten to add index [j]

like image 129
Imran Hossain Avatar answered Feb 13 '26 10:02

Imran Hossain


// Loop over rows
for (var i = 0; i < tableArr.length; i++) {
  var row = tableArr[i];
 // loop over columns
   for( var j =0; j<row.length; j++){
     //create each column and append to row
   }
  // append row to table body

}
// append table body to DOM

For performance reasons you want to write to the DOM only once and create the table in memory first.

like image 37
Tamb Avatar answered Feb 13 '26 08:02

Tamb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!