Nested Table with nested td children without headers to Json

Hi I need help to convert to JSON

    <table>
    <thead>
            <tr >
                <th class="product-remove">&nbsp;</th>
                <th class="product-thumbnail">&nbsp;</th>
                <th class="product-name">Product</th>
                <th class="product-price">Price</th>
                <th class="product-qty">Quantity</th>
            
            </tr>
        </thead>
        <tbody>

      <tr class="cart_item">
<td>
  <a href=""class="prod">3way Connector Cable</a>
  <a href=""class="cat">Tech</a>
  <a href="" class="code">1245</a>
</td>
<td>
  <span class="price">14.99</span>
</td>
<td>
      <span class="qty">2</span>
</td>
      </tr>
  <tr class="cart_item">
<td>
  <a href=""class="prod">Red Shirt</a>
  <a href=""class="cat">Clothes</a>
  <a href="" class="code">5431</a>
</td>
<td>
  <span class="price">10.99</span>
</td>
<td>
          <span class="qty">1</span>
</td>
      </tr>
      </tbody>
</table>
<input id="btnTableToJson" type="button" value="To JSON" />

              my code so far 
 function CreateJson() {
    
    var quoteDetails = [];
    var $headers =  $("thead tr").find("th.product-name, th.product-price, th.product-qty"); 
    //console.log($headers);
    var $rows = $("tbody .cart_item").each(function(index) {
      $cells = $(this).find(".prod,.price, .qty");
      quoteDetails[index] = {};
    
    //console.log(quoteDetails[index]);
      $cells.each(function(cellIndex) {
      quoteDetails[index][$($headers[cellIndex]).html()] = $(this).html();

      });    
    });
var myObj = {};
myObj.quoteDetails = quoteDetails;
console.log(quoteDetails)
console.log(JSON.stringify(myObj));

           results 
          {"quoteDetails":

[{"Product":"3way Connector Cable","Price":"14.99","Quantity":"2"},
{"Product":"Red Shirt","Price":"10.99","Quantity":"1"}]}

But I need all the to be added as to the json as key:pair like this:

{"quoteDetails":
[{"Product":"3way Connector Cable","Price":"14.99","Quantity":"2", "category": "Tech", "code": "1245"},
{"Product":"Red Shirt","Price":"10.99","Quantity":"1", "category": "Clothes", "code": "5431"}}]}
Challenge the other remaining a tag don’t have header and they need to be looped through and added to each json object
I don’t have a lot of liberty in changing the structure of the tables.
Please assist on how I can do those

Leave a Comment