sam
sam

Reputation: 956

how to loop through json array to get the value in javascript

I have the below json object and i want to loop through it and display the value in a div. My json object and the function to run it is below

  photos = [{"photo1":"myimage1.jpg",
           "photo2":"myimg2.jpg",
           "photo3":"myimg3.jpg",
           "photo4":"myimg4.jpg",}]

           function showPhotoOnLoad(photos,$imgUrl){
           var $photoData = photos; 
           var photoLength = Object.keys($photoData[0]).length;
           var i, key;  
           var $containerWidth = 110;
           //alert(photoLength);
           if(photoLength >0){
               $(".mycarousel-container").show();
                 for (i in $photoData) {
                for (key in $photoData[i]) {
                  a = $photoData[i][key];
                imgsrc = $imgUrl = $imgUrl+a; 
                var div = $("<div class='mycarousel' style='left:"+left+"px'></div>");
                var imgPreview = "<img  class='myimg' src="+imgsrc+">";
                div = div.append(imgPreview);
                $(".carouser-inner").append(div);

                left = left+$containerWidth;

                }               
              }
           }                              
           //console.log($imgUrl);            
       }

After i run this function i got 4 div created as expected but only the first child of the div has image shown and the other 3 has broken img, i try to debug and i see var a which is suppose to be the img name like myimg1.jpg and the result i got is

`a=myimg1.jpg` //at first iteration of the for loop which make the img display correctly,
`a=myimg1.jpgmyimg2.jpg` //at the second iteration 
`a=myimg1.jpgmyimg2.jpgmyimg3.jpg` //at the third iteration
`a=myimg1.jpgmyimg2.jpgmyimg3.jpgmyimg4.jpg` //at the last iteration

What i want to get is like below so all div created will have the right link to the img

`a=myimg1.jpg` //at the first iteration
`a=myimg2.jpg` //at the second iteration 
`a=myimg3.jpg` //at the third iteration
`a=myimg4.jpg //at the last iteration

Upvotes: 0

Views: 137

Answers (4)

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93173

Enjoy ONE-LINE code that replaces almost All your code:

     $(photos.map((item)=>
          Object.keys(item).map((key)=>
               `<div class='mycarousel' style='left:${left}px'>
                     <img src="${item[key]}" class="myimg" />
                </div>`
         ).join('') 
     ).join('')).appendTo('.carouser-inner')

Known that : $(A).append(B) is the same of $(B).appendTo(A)

DEMO

enter image description here

Upvotes: 0

M.Tanzil
M.Tanzil

Reputation: 1995

Problem is with imgsrc = $imgUrl = $imgUrl + a;

Here is the working snippet

var photos = [{"photo1":"myimage1.jpg",
           "photo2":"myimg2.jpg",
           "photo3":"myimg3.jpg",
           "photo4":"myimg4.jpg"}];

            showPhotoOnLoad(photos,"imageurl");

           function showPhotoOnLoad(photos,$imgUrl){
           var $photoData = photos; 
           var photoLength =     Object.keys($photoData[0]).length;
           var i, key;  
           var $containerWidth = 110;
           //alert(photoLength);
           if(photoLength >0){
               $(".mycarousel-container").show();
                 for (i in $photoData) {
                for (key in $photoData[i]) {
                  a = $photoData[i][key];
                imgsrc = "a="+a; 
                var div = $("<div class='mycarousel' style='left:20px'></div>");
                var imgPreview = "<img  class='myimg' src="+imgsrc+">";
                div = div.append(imgPreview);
                $(".carouser-inner").append(div);
console.log(imgsrc);
               // left = left+$containerWidth;

                }               
              }
           }                              
           //console.log($imgUrl);            
       }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

brk
brk

Reputation: 50291

Use Object.keys.length to get the length of the object.

Use for..in to get value of each key

var photos = [{
  "photo1": "myimage1.jpg",
  "photo2": "myimg2.jpg",
  "photo3": "myimg3.jpg",
  "photo4": "myimg4.jpg",
}]

var _div = ("<div class='mycarousel' style='left:2px'></div>");
var _divCache = "";

if (Object.keys(photos).length > 0) { // will check if the length is greater than 0 
  $(".mycarousel-container").show()
    // loop through each of the key. 0 since photos is an array of object
  for (var keys in photos[0]) {
    //photos[0][keys] will return values
    var imgPreview = $("<img  class='myimg' alt='img' src='" + photos[0][keys] + "'>");
    $(".carouser-inner").append($(_div).append((imgPreview)[0]));
  }
}

JSFIDDLE

Upvotes: 0

Yasin Yaqoobi
Yasin Yaqoobi

Reputation: 2040

I am not sure what this line is doing. imgsrc = $imgUrl = $imgUrl + a; you can simply loop over your data like this given your array will have only one object. If it has more you need a for loop wrapping the current loop to get all the objects.

photos = [{"photo1":"myimage1.jpg",
           "photo2":"myimg2.jpg",
           "photo3":"myimg3.jpg",
           "photo4":"myimg4.jpg",}];

       function showPhotoOnLoad(photos,$imgUrl){
       var $photoData = photos[0]; 

       var $containerWidth = 110;
       //alert(photoLength);
       if($photoData.length >0){
           $(".mycarousel-container").show();
            for (var i in $photoData){

            imgsrc = $photoData[i];
            var div = $("<div class='mycarousel' style='left:"+left+"px'></div>");
            var imgPreview = "<img  class='myimg' src="+imgsrc+">";
            div = div.append(imgPreview);
            $(".carouser-inner").append(div);

            left = left+$containerWidth;

            }               
          }
       }                              
       //console.log($imgUrl);            
   }

Upvotes: 0

Related Questions