How to create an array with data from a table html?

0

I need to put the table html data in a array . The current scenario does not allow me to add class or id to the <td> tags (which would make it much easier), later I started the jquery code but I do not know how to proceed. HTML

<table id="tb1">
<thead>
    <tr>
        <th>Bola1</th>
        <th>Bola2</th>
        <th>Bola3</th>
    </tr>
</thead>
<tbody>
    <tr><td>3</td><td>10</td><td>5</td></tr>
    <tr><td>1</td><td>4</td><td>3</td></tr>
    <tr><td>3</td><td>2</td><td>6</td></tr>
</tbody>
</table>

JQUERY
    It would be something like this:

$(document).ready(function () {

        $('.btnok').on('click', function () {
            var dados = [];                
            var table = $("#tb1 tbody");

            table.find("tr").each(function (indice) {                    
                $(this).find('td').each(function (indice) {

                    dados[indice] = new Object();
                    dados[indice][indice] = $(this).text();

                });

            });
        });

});

I expect to return a JSON:

[
    {"Bola1":"3","Bola2":"10","Bola3":"5"},
    {"Bola1":"1","Bola2":"4","Bola3":"3"},
    {"Bola1":"3","Bola2":"2","Bola3":"6"}
]
    
asked by anonymous 27.11.2017 / 12:25

1 answer

1

You can create a function to check and assign table data to an object and then add it to a list. In the code below, I created a tableToJSON function that receives as a parameter the seletor of the table and returns a list of objects based on it.

console.log(tableToJSON("table"));

function tableToJSON(tableSelector){
  var array = new Array();
  var $thead = $(tableSelector).find("thead > tr > th");
  var $tbody =$(tableSelector).find("tbody > tr");

  $tbody.each(function(x){
    var obj = new Object();  
    var $row = $(this);
    $thead.each(function(i){
      var attributeName = $(this).text();
      obj[attributeName] = $row.find("td")[i].innerText
    });
    array.push(obj);
  });	 
  return array;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><table><thead><tr><th>Coluna1</th><th>Coluna2</th><th>Coluna3</th></tr></thead><tbody><tr><td>Teste1</td><td>Teste1</td><td>Teste3</td></tr><tr><td>Teste4</td><td>Teste5</td><td>Teste6</td></tr></tbody></table>

Seeworkingat JSFiddle

    
27.11.2017 / 13:15