jQuery read json and display sub-levels only if they exist

0

I would like to do a validation, make a for the first level and second level of a json, the second level should be printed only if there is this second level in the item of the current array. Ex json down:

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 printed on a for, and the second level would be only if they existed.

Any ideas?

    
asked by anonymous 12.07.2017 / 22:58

1 answer

2

You can do a recursive function that checks whether one of the keys is an object, for example with if (typeof prop === 'object') . One suggestion would look like this:

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);
    
12.07.2017 / 23:08