简体   繁体   中英

How can I loop through my JSON data using javascript?

How can I looping through my JSON data? If I try this, my code just gets 1 data, not all of it.

Here is my code:

$.getJSON('profil.json', function(data) {
    let skills = data.skills.graphicdesigner

    $.each(skills, function(i, data) {
       $('#designimg').append('<div class="col-4 pb-3"><img id="myImg" src="img/thumbs/'+ 
       data.image[i] +'" alt="Snow" style="width:100%;max-width:300px"><div id="myModal" 
       class="modal"><span class="close">&times;</span><img class="modal-content" id="img01"><div 
       id="caption"></div></div></div>');
    });
 });

And here my JSON:

skills":{
  "graphicdesigner": [
    {
        "label": "CorelDraw & Adobe Illustrator",
        "image": ["rimba.jpg","programmer.png","gallery1.jpg"]

    }
]

The issue here is image property inside graphicdesigner is another array, so you will need to loop through it also to get all the image strings like:

$.each(skills, function(i, data) {
  $.each(data.image, function(j, img) {

    // This is image string inside `image` array
    // Just add it to image src
    console.log( img );

    $('#designimg').append('<img id="myImg" src="img/thumbs/' + img + '" alt="Snow">');
  });
});

I have not added the full HTML string that you have inside append() method, but I hope you got the idea here.

You need to do another loop for each images as well.

  • First you loop your graphicdesigner array.
  • Then you loop your images from the item of your first loop.
$.getJSON('profil.json', function(data) {
    let skills = data.skills.graphicdesigner

    $.each(skills, function(i, data) {
        $.each(data.image, function(y, image) {
            $('#designimg').append('<div class="col-4 pb-3"><img id="myImg" src="img/thumbs/'+ 
            image + '" alt="Snow" style="width:100%;max-width:300px"><div id="myModal" ' +
            'class="modal"><span class="close">&times;</span><img class="modal-content" ' +
            'id="img01"><div id="caption"></div></div></div>');
        })
    });
});

It is not tested, but it should be something like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM