Separate a JSON array into columns and rows

Asked

Viewed 841 times

1

I’m getting a JSON array in the back end this way :

inserir a descrição da imagem aqui

{
    "idDistrito": "23",
    "nome": "rere",
    "codigoDne": "154545",
    "cns": "565665",
    "entidade": {
        "idEntidade": "1",
        "nome": "Entidade 01"
    },        
    "emissaoProfissional": "07/11/2017"

}

I would like to know how to separate attributes from variables to assemble a table where attributes would be column and variables would be rows.

  • If I understand correctly you want to mount a table through the result of a Json ?

  • @Marconi yes that’s the idea.

  • You can post your Json (or at least part of it) in the code instead of the image?

  • yes, I’ll edit the question.

  • @Marconi edited the question and included the code json

  • I think he meant the code that generates Json

  • The question is: structure of all objects within the array will be the same or can differentiate? I mean, if there is an object that can come with nome and others not...

  • @Lucascosta in the case of this page some items are not mandatory, for example the codigoDne may come empty. but the attribute will come.

  • @Eduardokrakhecke You are using Angularjs?

  • I use Angularjs yes.. But some functions prefer Javascript

  • @Eduardokrakhecke I think what you need is in the answer below!

Show 6 more comments

1 answer

2


You can use the method .each(), it is designed to make DOM loop constructs concise and less error-prone. When called iterate on the DOM elements that are part of the object jQuery. Each time the callback is executed, the current loop iteration is passed, starting from 0.

var html_ = "";
$.each( msg, function( key, value ) {
    html_ += "<tr>";
    html_ += "<td>"+value.idDistrito+"</td>";
    html_ += "<td>"+value.nome+"</td>";
    html_ += "<td>"+value.campox+"</td>";
    html_ += "<td>"+value.campoy+"</td>";
    html_ += "</td></tr>";
    // ou ao inves da variavel html pode usar o 
    $("#tabela").last().append("<tr><td>"+value.idDistrito+"</td><td>"+value.nome+"</td><td>"+value.campox+"</td>td>"+value.campoy+"</td></td></tr>");
});
$("#tabela").html(html_);
  • 1

    Why do you declare html and uses html_?

  • Oops my mistake, thanks for noticing, I’ve already edited

Browser other questions tagged

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