List Javascript objects in a table

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 it inside a tbody. But I can not find a solution wherever I look. Att.

    
asked by anonymous 05.09.2015 / 21:46

1 answer

5

You will need to iterate through 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: link

So since relatorios is an array, you go one by one with .forEach() and every row / element of that array creates a new tr for the table.

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

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

    
05.09.2015 / 21:59