2

Since a few hours I'm trying to find the best way to build the tbody section of my html <table> 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>
0

3 Answers 3

3

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Your solution is what I needed. Your code is short and powerful. I like it so much. Thank you.
1

I'd put this in your body-element. Go through each row in your array, then within each row through each column and add it one by one.

--> Note that the number of rows is determined by the number of rows your first array-element has.

    <body>
        <style>
            table, tr, td {
                border: solid 1px;
            }
        </style>
        <script>
        (function() {

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

        var table = document.createElement("table");

        for (i = 0; i < arParent[0].length; i++) {
            var row = document.createElement("tr");
            for (j = 0; j < arParent.length; j++) {
                var column = document.createElement("td");
                var content = document.createTextNode(arParent[j][i]);
                column.appendChild(content);
                row.appendChild(column);
            }
            table.appendChild(row);
        }

        document.body.appendChild(table);
        })();
    </script>
<body>

Comments

1

I would first transform this non-table-like data into rows. Then render the rows in the normal fashion.

To wit:

var arParent = [
  ["col1a", "col1b", "col1c", "<b>&amp;</b>"],
  ["col2a", "col2b", "col2c", "<a href='http://google.com'>googles</a>"]
]


function transformData(arr) {
  // transform columns into rows
  var rows = [];
  for (var i = 0, iLen = arr.length; i < iLen; i++) {
    var cols = arr[i];
    for (var j = 0, jLen = cols.length; j < jLen; j++) {
      var row;
      if (i === 0) {
        row = {
          columns: []
        };
        rows.push(row);
      } else {
        row = rows[j];
      }
      var col = cols[j];
      row.columns.push(col);
    }
  }
  return rows;
}

// from http://stackoverflow.com/questions/1219860/html-encoding-in-javascript-jquery
function htmlEscape(str) {
    return String(str)
        .replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');
}

function renderTableData(rows) {
  var html = [];
  for (var r = 0, rLen = rows.length; r < rLen; r++) {
    var row = rows[r];
    html.push("<tr>");
    for (var c = 0, cLen = row.columns.length; c < cLen; c++) {
      var col = row.columns[c];
      html.push("<td>");
      html.push(htmlEscape(col));
      html.push("</td>");
    }
    html.push("</tr>");
  }
  var tbody = document.getElementById('tabledata');
  tbody.innerHTML = html.join('');
}

var rows = transformData(arParent);

console.log(JSON.stringify(rows));

renderTableData(rows);
td {
  padding: 2px 4px;
  font-family: "Segoe UI", Arial, sans-serif;
  border: 1px solid #ccc;
}
<table>
  <tbody id='tabledata'>
  </tbody>
</table>

You can write this much more concisely, but I purposely broke it into small simple statements so that you could hopefully follow along and understand the routines.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.