jQuery read json and show sublevels only if they exist

Asked

Viewed 176 times

0

I would like to do a validation, do a printout for the first level and second level of a json, the second level should be printout only if there is that second level in the current array item. Ex de json a bass:

content = {
  "primeiroNivel0": {
    "title":"Titulo Bonito",
    "id":"001",
    "url":"souUmaUrl",
     "segundoNível":  {                                                                              
         "title":"Titulo subnivel",
          "id":"001.01",
          "url":"souUmaUrlDeSubnivel",
          }
},
"primeiroNivel1": {
    "title":"Titulo Bonito1",
    "id":"002",
    "url":"souUmaUrl2"
  }
}

The first levels would be imprinted on one, and the second level of those would be only if they existed.

Any idea?

1 answer

2


You can make a recursive function that checks if one of the keys is an object, for example with if (typeof prop === 'object'). A suggestion would be so:

var content = {
  "primeiroNivel0": {
    "title": "Titulo Bonito",
    "id": "001",
    "url": "souUmaUrl",
    "segundoNível": {
      "title": "Titulo subnivel",
      "id": "001.01",
      "url": "souUmaUrlDeSubnivel",
    }
  },
  "primeiroNivel1": {
    "title": "Titulo Bonito1",
    "id": "002",
    "url": "souUmaUrl2"
  }
}

function mostrarConteudo(obj, nivel) {
  Object.keys(obj).forEach(function(chave) {
    var prop = obj[chave];
    if (typeof prop === 'object') mostrarConteudo(prop, chave);
    else console.log(nivel, '>', chave, prop);
  });
}

mostrarConteudo(content);

Browser other questions tagged

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