-1

I have this JSON and I don't know how to access to elements in productList . This is the JSON

[
{
    "id": 1,
    "name": "sala1",
    "deleted": "NODELETED",
    "sectionList": [
        {
            "id": 1,
            "name": "seccion1",
            "methodList": [],
            "frecuencyList": [],
            "productList": [
                {
                    "id": 1,
                    "name": "lejia",
                    "deleted": "NODELETED"
                },
                {
                    "id": 3,
                    "name": "agua",
                    "deleted": "NODELETED"
                },
                {
                    "id": 4,
                    "name": "cal",
                    "deleted": "NODELETED"
                }
            ],
            "deleted": "NODELETED"
        },
        {
            "id": 2,
            "name": "seccion2",
            "methodList": [],
            "frecuencyList": [],
            "productList": [
                {
                    "id": 1,
                    "name": "lejia",
                    "deleted": "NODELETED"
                }
            ],
            "deleted": "NODELETED"
        }
    ]
}

]

I'm using this :

$.getJSON('my url' , function(data) {

$.each(data , function(key, val)
{
    console.log("Value of ProductList-> " + data['productList'].name );
});

}); 

Please is the first time that I use JSON with other arrays inside and I'm lose. Thank to all !!!

TSW1985
  • 1,179
  • 2
  • 10
  • 13
  • possible duplicate of [Serializing to JSON in jQuery](http://stackoverflow.com/questions/191881/serializing-to-json-in-jquery) – brandonscript Dec 25 '13 at 01:06

3 Answers3

2

data[0].sectionList[0].productList will give you the first item in your collections first item in its sectionList collection's productlist.

$.getJSON('my url' , function(data) {

   $.each(data , function(key, val)
   {
    console.log("Value of ProductList-> " + val.sectionList[0].productList.name );
   });

}); 

To get each product list you'll need another inner loop.

   $.getJSON('my url' , function(data) {

   $.each(data , function(key, val)
   {
    $.each(val.sectionList , function(k, v){
      console.log(v.productList.name);
    }
   });

}); 
bluetoft
  • 5,373
  • 2
  • 23
  • 26
0

If you want to avoid using jQuery loops, you can do this simply with vanilla JS:

var productList = data[0].sectionList[0].productList;

for (var i = 0, l = productList.length; i < l; i++) {
  console.log('Value of ProductList-> ' + productList[i].name);
}
Andy
  • 61,948
  • 13
  • 68
  • 95
0

you can also try this:

jQuery.each(data , function(key, val)
{
    jQuery.each(val['sectionList'] , function(sectionIndex, section){
        jQuery.each(section['productList'] , function(index, product){
            alert("Value of ProductList-> " + product.name );
        });                
    });

});
Mehran Hatami
  • 12,723
  • 6
  • 28
  • 35