JSFiddle - React, Tailwind, and code Playground

by awolf2904

HTML

<table id="cartGrid">
  <thead>
       <tr>
          <th>Item Description</th>
          <th>Qty</th>
          <th>Unit Price</th>
          <th>Ext Price</th>
       </tr>
  </thead>
<tbody>
    <tr><td>Old Lamp</td><td>1</td><td>107.00</td><td>107.00</td></tr>
    <tr><td>Blue POst</td><td>2</td><td>7.00</td><td>14.00</td></tr>
</tbody>
</table>

<h2>Output data (debugging only):</h2>
<pre id="out"></pre>

JavaScript

var tableData = [],
    objTmpl,
    objMap = [];

$("table#cartGrid tr").each(function() {
    var $row = $(this),
        key = '';
    
    //console.log($row.children().filter('th'));
    //check if heading
    var $headings = !objTmpl ? $row.children().filter('th'): []; // do this test only if objTmpl is undefined!
    //console.log($headings);
    if ( $headings.length > 0 ) {
        objTmpl = {};
        $headings.each(function(index) {
            key = $(this).text().replace(' ', '_'); 
            objTmpl[key] = '';
            objMap[index] = key;
        });
        //console.log('heading found', objTmpl, objMap);
    } else {
        // not heading --> data row
        var curRowDataObj = JSON.parse(JSON.stringify(objTmpl)); // copy tmpl.
        
        $row.children().each(function(index) {
            curRowDataObj[objMap[index]] = $(this).text();
        });
        
        tableData.push(curRowDataObj);
    }
});

//console.log(tableData);
$('#out').html(JSON.stringify(tableData, null, 4));