How to create an array of data from an html table?

Asked

Viewed 962 times

1

I need to input the data from table html in a array. The current scenario doesn’t allow me to add class or id for the tags <td> (which would make me much easier), later I started the code jquery but I don’t 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 hope to return a JSON:

[
    {"Bola1":"3","Bola2":"10","Bola3":"5"},
    {"Bola1":"1","Bola2":"4","Bola3":"3"},
    {"Bola1":"3","Bola2":"2","Bola3":"6"}
]
  • can give an example of the resulting array you expect to have?

  • I changed the post and added an example of what I want to return (JSON)

1 answer

2


You can create a function to check and assign the table data to an object and then include it in a list. In the code below, I created a function tableToJSON which 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>Coluna 1</th>
    <th>Coluna 2</th>
    <th>Coluna 3</th>
  </tr>
</thead>
<tbody>
  <tr><td>Teste 1</td><td>Teste 1</td><td>Teste 3</td></tr>
  <tr><td>Teste 4</td><td>Teste 5</td><td>Teste 6</td></tr>
  
</tbody>
</table>

See working on Jsfiddle

  • Perfect! Just what I needed. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.