Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert table to array in JavaScript without using jQuery

I need to convert the table grid i created into an multidimensional array according to the content inside the table. Array would be in format like:

 var array = [
               [column,column,...],
               [column,column,...],
               ...
              ];

How do I do this without using jQuery, using plain JavaScript? All answers I found was in jQuery.

JSFiddle.

like image 516
Pratish Shrestha Avatar asked Dec 18 '15 06:12

Pratish Shrestha


2 Answers

Presuming your table is something like the one below, you can convert that into an array of arrays using the rows collection of the table and cells collection of the rows:

function tableToArray(table) {
  var result = []
  var rows = table.rows;
  var cells, t;

  // Iterate over rows
  for (var i=0, iLen=rows.length; i<iLen; i++) {
    cells = rows[i].cells;
    t = [];

    // Iterate over cells
    for (var j=0, jLen=cells.length; j<jLen; j++) {
      t.push(cells[j].textContent);
    }
    result.push(t);
  }
  return result; 
}
    
    document.write(JSON.stringify(tableToArray(document.getElementsByTagName('table')[0])));
<table>
  <tr>
    <td>one<td>two<td>three
  <tr>
    <td>one<td>two<td>three
  <tr>
    <td>one<td>two<td>three
</table>

Or if like concise code, use some ES5 goodness:

function tableToArray(table) {
  var result  = [].reduce.call(table.rows, function (result, row) {
      result.push([].reduce.call(row.cells, function(res, cell) {
          res.push(cell.textContent);
          return res;
      }, []));
      return result;
  }, []);
  return result;
}
like image 158
RobG Avatar answered Nov 16 '22 17:11

RobG


With qSA and Array.prototype.map is pretty simple.

var tableInfo = Array.prototype.map.call(document.querySelectorAll('#tableId tr'), function(tr){
  return Array.prototype.map.call(tr.querySelectorAll('td'), function(td){
    return td.innerHTML;
    });
  });
like image 19
MinusFour Avatar answered Nov 16 '22 18:11

MinusFour