Home > database >  How to make a loop with a Jquery subarray Json?
How to make a loop with a Jquery subarray Json?

Time:02-02

I have this array and I need to get the public_id and format values

{"resources":[{"public_id":"samples/3_zm3ex0","version":1643650862,"format":"jpg","width":4000,"height":3000,"type":"upload","created_at":"2022-01-31T17:41:02Z"},{"public_id":"mggvuz0xisg2nzkldbvx","version":1643520511,"format":"jpg","width":500,"height":549,"type":"upload","created_at":"2022-01-30T05:28:31Z"},{"public_id":"samples/cloudinary-group","version":1643517184,"format":"jpg","width":3000,"height":1526,"type":"upload","created_at":"2022-01-30T04:33:04Z"}],"updated_at":"2022-01-31T18:28:07Z"}

I try to do it like this but without success

 $(document).ready(function() {
            $("#fetch").click(function(event) {
                $.getJSON('https://res.cloudinary.com/dkx20emez/image/list/dom.json', function(emp) {
                    $('#display').html('<p> Name: '   emp.resources.public_id   '</p>');
$('#display').html('<p> Name: '   emp.resources.format   '</p>');
                   
                    
                   
                });
            });
        });

I appreciate your help

CodePudding user response:

The ressources attributes is an array so you have to loop each element in it. Your code should be like this :

$(document).ready(function() {
    $("#fetch").click(function(event) {
        $.getJSON('https://res.cloudinary.com/dkx20emez/image/list/dom.json', function(emp) {
          //the attribute resource is an array so you have to loop each element in it
          emp.resources.forEach(function(element){   
            var publicid = element.public_id;
            var format = element.format;
            $('#display').append('<div><p> Name: '   publicid   '</p><p> Name: '   format   '</p></div>');
          });

        });
    });
});
  •  Tags:  
  • Related