zm455 zm455 - 6 months ago 34
HTML Question

Javascript: build html table from 2 arrays

Since a few hours I'm trying to find the best way to build the tbody section of my html from two javascript arrays.

Note: I may not use Jquery.

My array contains 2 childs arrays:

var arParent = [
["col1a", "col1b", "col1c"],
["col2a", "col2b", "col2c"]
]


I would need something like:

<tr>
<td>col1a</td>
<td>col2a</td>
</tr>
<tr>
<td>col1b</td>
<td>col2b</td>
</tr>
<tr>
<td>col1c</td>
<td>col2c</td>
</tr>

Answer

You can first convert rows to columns and then just add to table

var ar = [
  ["col1a", "col1b", "col1c"],
  ["col2a", "col2b", "col2c"]
], table = document.querySelector('table tbody');

//Convert rows to columns
var r = ar[0].map(function(col, i) {
  return ar.map(function(row) {
    return row[i];
  });
});

//Add data to table
r.forEach(function(e) {
  table.innerHTML += '<tr><td>' + e[0] + '</td><td>' + e[1] + '</td></tr>'
})
<table>
  <tbody></tbody>
</table>