How to access sub elements in AJAX and jQuery?

1

Well I'm working with AJAX , JavaScript and of course jQuery , I've managed to bring the data response from the database so access and show the main data of this, the problem is that I have not been able to access the child elements that each parent has, I do not know how to do it, I have already tried several things and since yesterday I have been trapped, I will leave you my code so they can understand what I have done.
As you can see in the code I get the names of the parent categories, I display them with jQuery and inserting them in the HTML and everything looks good, the thing is and the sub-categories ?
Here JSON

[
  {
    "id": "28",
    "name": "Restaurante",
    "activo": "true",
    "sub": [
      {
        "id": "29",
        "name": "Comida Casera"
      },
      {
        "id": "38",
        "name": "Cafetería"
      }
    ]
  },
  {
    "id": "30",
    "name": "Música",
    "activo": "true",
    "sub": [
      {
        "id": "31",
        "name": "Academia de Música"
      }
    ]
  },
  {
    "id": "33",
    "name": "Bienstar sexual ",
    "activo": "true",
    "sub": [
      {
        "id": "34",
        "name": "Gel íntimo "
      },
      {
        "id": "66",
        "name": "Juguetes para adultos"
      }
    ]
  },
  {
    "id": "41",
    "name": "Moda",
    "activo": "true",
    "sub": [
      {
        "id": "40",
        "name": "Mochilas"
      },
      {
        "id": "67",
        "name": "Zapatos Hombre"
      }
    ]
  },
  {
    "id": "59",
    "name": "Auto",
    "activo": "true",
    "sub": [
      {
        "id": "60",
        "name": "Accesorio para automóviles "
      },
      {
        "id": "61",
        "name": "Lavado para automóviles "
      }
    ]
  },
  {
    "id": "63",
    "name": "Belleza",
    "activo": "true",
    "sub": [
      {
        "id": "64",
        "name": "Salón de Belleza"
      },
      {
        "id": "65",
        "name": "Productos de Belleza"
      }
    ]
  },
  {
    "id": "68",
    "name": "Deporte",
    "activo": "true",
    "sub": [
      {
        "id": "69",
        "name": "Gimnasios"
      }
    ]
  }
]

Here the JavaScript.

        $.ajax({
        type: 'GET',
        url: 'http://www.kupomcity.com/gamma/api_v2.php?
        _opt=categorias&_act=view',
        dataType: 'json',
        data: null,
        beforeSend: function() {
          //alert('Fetching....');
        },
        success: function() {
          //alert('Fetch Complete');
        },
        error: function() {
          //alert('Error');
        },
        complete: function(data) {   
          var ul = $("<ul class='navbar-nav'>");
          for (var j = 0; j  < data.responseJSON.length ; j++) {
              ul.append("<li class='dropdown'><a href='templates/interior-categoria.html' class='nav-link' data-toggle='dropdown'>" + data.responseJSON[j].name + "<b class='caret'></b></a><ul class='dropdown-menu'><li><a href='templates/interior-categoria.html'>" + data.responseJSON[j].name + "</a></li></ul></li>");
          } 

          $("#categorias").append(ul);   
          if (JSON.stringify(data.statusText) == '"OK"') {
            //$('#cupones_usados').text(JSON.stringify(data.responseJSON));
            //alert("cupones: " +JSON.stringify(data.responseJSON));
          }
        }
      });
    
asked by Nelson Jara Torres 04.08.2017 в 18:18
source

3 answers

0

This code can be worked on, to make it more dynamic, but it is for you to have an idea.

var responseJSON = [
  {
    "id": "28",
    "name": "Restaurante",
    "activo": "true",
    "sub": [
      {
        "id": "29",
        "name": "Comida Casera"
      },
      {
        "id": "38",
        "name": "Cafetería"
      }
    ]
  },
  {
    "id": "30",
    "name": "Música",
    "activo": "true",
    "sub": [
      {
        "id": "31",
        "name": "Academia de Música"
      }
    ]
  },
  {
    "id": "33",
    "name": "Bienstar sexual ",
    "activo": "true",
    "sub": [
      {
        "id": "34",
        "name": "Gel íntimo "
      },
      {
        "id": "66",
        "name": "Juguetes para adultos"
      }
    ]
  },
  {
    "id": "41",
    "name": "Moda",
    "activo": "true",
    "sub": [
      {
        "id": "40",
        "name": "Mochilas"
      },
      {
        "id": "67",
        "name": "Zapatos Hombre"
      }
    ]
  },
  {
    "id": "59",
    "name": "Auto",
    "activo": "true",
    "sub": [
      {
        "id": "60",
        "name": "Accesorio para automóviles "
      },
      {
        "id": "61",
        "name": "Lavado para automóviles "
      }
    ]
  },
  {
    "id": "63",
    "name": "Belleza",
    "activo": "true",
    "sub": [
      {
        "id": "64",
        "name": "Salón de Belleza"
      },
      {
        "id": "65",
        "name": "Productos de Belleza"
      }
    ]
  },
  {
    "id": "68",
    "name": "Deporte",
    "activo": "true",
    "sub": [
      {
        "id": "69",
        "name": "Gimnasios"
      }
    ]
  }
];


for (var i=0 ; i<1; i++) {
    $.each(responseJSON, function (ind, elem) {
  console.log(elem.sub[i]);
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
    
answered by 04.08.2017 / 19:31
source
1

Eye! you access property name in this way

data.responseJSON[j].name

Therefore you should access sub like this:

data.responseJSON[j].sub

Sub, is an arrangement with objects with the format:

{ id : '', name : '' }

therefore you should go through it to get the subcategories.

for (var s = 0; s  < data.responseJSON[j].sub.length ; s++) {
     var subcategoria = data.responseJSON[j].sub[s];
     /* Acceder a sus propiedades
     subcategoria.id
     subcategoria.name */

You could also use forEach to boost the use of the jquery

var json = [
  {
    "id": "28",
    "name": "Restaurante",
    "activo": "true",
    "sub": [
      {
        "id": "29",
        "name": "Comida Casera"
      },
      {
        "id": "38",
        "name": "Cafetería"
      }
    ]
  },
  {
    "id": "30",
    "name": "Música",
    "activo": "true",
    "sub": [
      {
        "id": "31",
        "name": "Academia de Música"
      }
    ]
  },
  {
    "id": "33",
    "name": "Bienstar sexual ",
    "activo": "true",
    "sub": [
      {
        "id": "34",
        "name": "Gel íntimo "
      },
      {
        "id": "66",
        "name": "Juguetes para adultos"
      }
    ]
  },
  {
    "id": "41",
    "name": "Moda",
    "activo": "true",
    "sub": [
      {
        "id": "40",
        "name": "Mochilas"
      },
      {
        "id": "67",
        "name": "Zapatos Hombre"
      }
    ]
  },
  {
    "id": "59",
    "name": "Auto",
    "activo": "true",
    "sub": [
      {
        "id": "60",
        "name": "Accesorio para automóviles "
      },
      {
        "id": "61",
        "name": "Lavado para automóviles "
      }
    ]
  },
  {
    "id": "63",
    "name": "Belleza",
    "activo": "true",
    "sub": [
      {
        "id": "64",
        "name": "Salón de Belleza"
      },
      {
        "id": "65",
        "name": "Productos de Belleza"
      }
    ]
  },
  {
    "id": "68",
    "name": "Deporte",
    "activo": "true",
    "sub": [
      {
        "id": "69",
        "name": "Gimnasios"
      }
    ]
  }
];
$.each(json, function (ind, elem) {
  $.each(elem.sub, function (i, subcategoria) {
    console.log("Subcategoria : " + subcategoria.name);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
answered by 04.08.2017 в 19:27
0

As a general rule, everything in a JSON has brackets is a array , and you can access it with brackets, and everything in a JSON that has keys is a object , and you can access with dot notation.

Assuming this JSON:

var json = JSON.parse('[{"id":28, "name":"Carlos", "surname":"Gomez"}]');

You can access the last name like this:

var apellido = json[0].surname; // "Gomez"

Keep in mind that according to the JSON you copied, all the content is inside the first element of an array, so whatever you do, start with variable [0].

For example, to access the object that in your example says "homemade food":

var id = variable[0].sub[0].id; // "29"
var nombre = variable[0].sub[0].name; // "Comida casera"
    
answered by 04.08.2017 в 19:31