How to get the value of each TD within each TR dynamically using jQuery?

1

I have the following sample HTML:

<tr>
    <td>Futebol</td>
    <td>Campo</td>
</tr>
<tr>
    <td>Volei</td>
    <td>Quadra</td>
</tr>
<tr>
    <td>Tenis</td>
    <td>Saibro</td>
    <td>Campo</td>
</tr>
<tr>
    <td>Natação</td>
    <td>Piscina</td>
</tr>
<tr>
    <td>Ciclismo</td>
    <td>Rua</td>
</tr>

I would need to loop through tr by taking the value of each td and having a json something like this:

"esportes":[
{
    "esporte":"Futebol",
    "ambiente":"Campo"
},
{
    "esporte":"Volei",
    "ambiente":"Quadra"
},
{
    "esporte":"Tenis",
    "ambiente":"Saibro",
    "ambiente":"Campo"
},
{
    "esporte":"Ciclimo",
    "ambiente":"Rua"
}]

How could I do this with jQuery? I just did this for now but I do not know how to continue from here (if I'm on the way). Turning to JSON is not quite the problem, the biggest problem would be to get the values right, each sport with its usage environment:

$("#tableEsportes > tbody > tr").each(function(){ 
    console.log($(this).text());
});
    
asked by anonymous 28.02.2018 / 13:33

3 answers

8

First, JSON can not have repeated keys:

"ambiente":"Saibro",
"ambiente":"Campo"

I suggest this structure:

[
    {
        "esporte":"Futebol",
        "ambiente": ["Campo"]
    },
    {
        "esporte":"Volei",
        "ambiente": ["Quadra"]
    },
    {
        "esporte":"Tenis",
        "ambiente": ["Saibro", "Campo" ]
    },
    {
        "esporte":"Ciclismo",
        "ambiente": ["Rua"]
    }
]

Then you can use the :first-child selector to get only the first <td> that is the child of <tr> and the :not(:first-child) selector to get the other elements that will be the places:

$(function () {
    var esportesJson = { "esportes": [] };

    $("#tableEsportes tr").each(function () {
        var esporte = $("td:first-child", this);
        var ambientes = [];
        
        $("td:not(:first-child)", this).each(function () {
            ambientes.push($(this).text());
        });
        
        esportesJson.esportes.push({
            "esporte": esporte.text(),
            "ambiente": ambientes
        });
    });

    console.log(esportesJson);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><tableid="tableEsportes">
<tr>
    <td>Futebol</td>
    <td>Campo</td>
</tr>
<tr>
    <td>Volei</td>
    <td>Quadra</td>
</tr>
<tr>
    <td>Tenis</td>
    <td>Saibro</td>
    <td>Campo</td>
</tr>
<tr>
    <td>Natação</td>
    <td>Piscina</td>
</tr>
<tr>
    <td>Ciclismo</td>
    <td>Rua</td>
</tr>
</table>
    
28.02.2018 / 13:54
2

A Guilherme's answer is very good, but another way to be doing using pure JavaScript:

var arrayTr = document.body.querySelectorAll('#tableEsportes > tbody > tr');
var array = [];

for (let i = 0, j = arrayTr.length; i < j; i++) {
    let obj = {};
    let ambientes = [];
    let tr = [];

    tr = arrayTr[i];
    obj.esporte = tr.children[0].textContent;

    for (let x = 1, y = tr.children.length; x < y; x++) {
        ambientes.push(tr.children[x].textContent);
    }

    obj.ambiente = ambientes;
    array.push(obj);
}

console.log(JSON.stringify(array));
<table id="tableEsportes"> 
<tr>
    <td>Futebol</td>
    <td>Campo</td>
</tr>
<tr>
    <td>Volei</td>
    <td>Quadra</td>
</tr>
<tr>
    <td>Tenis</td>
    <td>Saibro</td>
    <td>Campo</td>
</tr>
<tr>
    <td>Natação</td>
    <td>Piscina</td>
</tr>
<tr>
    <td>Ciclismo</td>
    <td>Rua</td>
</tr>
</table>

Explaining

  • Return all rows with document.querySelectorAll
  • By deducing that the first column will always be the sport, the next one should be the environment, so use another to go through the rest of the columns.
  • Use JSON.stringify to transform your array in a string in the format JSON .
28.02.2018 / 14:31
0

You can do this: create an array and add the elements to it and then serialize:

var obj = {
esportes: []
};
$("#tableEsportes > tbody > tr").each(function() {
var linha = {
    esporte: $(this).find('td').eq(0).text(),
    ambiente: $(this).find('td').eq(1).text()
}
obj.esportes.push(linha);
});

console.log(JSON.stringify(obj));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><tableid="tableEsportes">

<tr>
    <td>Futebol</td>
    <td>Campo</td>
</tr>
<tr>
    <td>Volei</td>
    <td>Quadra</td>
</tr>
<tr>
    <td>Tenis</td>
    <td>Saibro</td>
    <td>Campo</td>
</tr>
<tr>
    <td>Natação</td>
    <td>Piscina</td>
</tr>
<tr>
    <td>Ciclismo</td>
    <td>Rua</td>
</tr>
</table>
    
28.02.2018 / 13:50