Get nested array items to append to new column in HTML Table

Viewed 270

I'm trying to append items from a 2D array into a table, but everything is appearing in the one column on the left. How can I separate tableDataArr[1] to start loading into the next column across?

Javascript

let names = []; //populated dynamically
let language = []; //populated dynamically 
let tableDataArr = [names, language];

function renderData() {
  for (let i = 0; i < tableDataArr.length; i++) {
    tableDataArr[i].forEach(j => {
      let newRow = document.createElement("tr");
      newRow.className = "row";
      newRow.innerHTML = `<td class='cell'>${j}</td>`;
      leftTable.appendChild(newRow);
    });
  }
}

HTML

<div class='left-tbl-wrap'>
  <table class='table' id='left-table'>
    <tr class='row'>
      <th class='th'>Name</th>
      <th class='th'>Language</th>
      <th class='th'>Latest tag</th>
      <th class='th'><span class='delete'></span></th>
    </tr>
  </table>
</div>
2 Answers

For each iteration add name and language to the same row, then insert that row into table.

I added some elements in names and languages array to demostrate

let names = ["name1", "name2", "name3"]; //populated dynamically
let language = ["language1", "language2", "language3"]; //populated dynamically 
let tableDataArr = [names, language];
const leftTable = document.querySelector("#left-table");

function renderData() {
  tableDataArr[0].forEach((j, i) => {
    let newRow = document.createElement("tr");
    newRow.className = "row";
    newRow.innerHTML = `<td class='cell'>${j}</td><td class='cell'>${tableDataArr[1][i]}</td>`;
    leftTable.appendChild(newRow);
  });
}

renderData();
<div class='left-tbl-wrap'>
  <table class='table' id='left-table'>
    <tr class='row'>
      <th class='th'>Name</th>
      <th class='th'>Language</th>
      <th class='th'>Latest tag</th>
      <th class='th'><span class='delete'></span></th>
    </tr>
  </table>
</div>

It should be like that

function renderData() {
    for (let i = 0; i < tableDataArr.length; i++) {
      let newRow = document.createElement("tr");
      tableDataArr[i].forEach(j=> {
        newRow.className = "row";
        newRow.innerHTML = `<td class='cell'>${j}</td>`;
        leftTable.appendChild(newRow);
      });
    }
}

Because you may do not need to iterate table row in the second loop. If you do like that it will be add each row with only one table data.

Related