List Javascript objects in a table

Asked

Viewed 1,476 times

1

Good afternoon. I have an object:

var relatorios = [
        { "Data": "28/08/2015", "Descricao": "Visita a Cliente", "Classificacao": "Class.2", "Valor": "R$435,00", "Verba": "RH", "Comentario": "Cliente A" },
        { "Data": "15/05/2013", "Descricao": "Apresentação", "Classificacao": "Class.4", "Valor": "R$328,00", "Verba": "Financeiro", "Comentario": "Cliente S" },
        { "Data": "19/10/2014", "Descricao": "Visita e Apresentação", "Classificacao": "Class.7", "Valor": "R$548,78", "Verba": "Diretoria", "Comentario": "Cliente D" },
        { "Data": "11/04/2015", "Descricao": "Proposta", "Classificacao": "Class.34", "Valor": "R$369,22", "Verba": "Comercial", "Comentario": "Cliente F" },
        { "Data": "12/12/2015", "Descricao": "Visita", "Classificacao": "Class.2", "Valor": "R$120,20", "Verba": "RH", "Comentario": "Cliente G" },
        { "Data": "25/06/2015", "Descricao": "Evento", "Classificacao": "Class.1", "Valor": "R$125,00", "Verba": "Comercial", "Comentario": "Cliente H" },
        { "Data": "29/07/2015", "Descricao": "Fechar Venda", "Classificacao": "Class.9", "Valor": "R$333,33", "Verba": "comercial", "Comentario": "Cliente J" }
        ];

And I would like to list it on a table, actually, just put inside a tbody. But I can’t find solution wherever I look. Att.

1 answer

5

You will need to iterate this array and add elements.

relatorios.forEach(function (relatorio) {
    var tr = document.createElement('tr');
    for (var campo in relatorio) {
        var td = document.createElement('td');
        td.innerHTML = relatorio[campo];
        tr.appendChild(td);
    };
    tbody.appendChild(tr);
});

jsFiddle: http://jsfiddle.net/gsupdtp9/

Thus, since relatorios is an array, you go one by one with the .forEach() and each row/element of this array creates a new one tr to the table.

Then you also iterate the object each report is, and create a new td insert the value with td.innerHTML = relatorio[campo];.

Then just insert the created element into the element where it belongs.

  • 1

    +1 for not using Jquery and for manipulating DOM instead of concatenating string.

Browser other questions tagged

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