zana
zana

Reputation: 269

cannot get data through each()

Sorry I'm still quite new to this. I am having trouble getting the data from this array in my ajax success. I am trying to iterate through productVariantImages to get the two imagePath but I am only able to get one which is from id 496. Below is the sample of the array.

Also if possible I would like to use objects instead of array

[1] => Array
    (
      [id] => 194
      [sku] => Apple SKU2
      [variantName] => Pear 2
      [productVariantImages] => Array
      (
         [0] => Array
           (
             [id] => 496
             [imageName] => Apples in season.png
             [imagePath] => http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png
             [visible] => 1
             [featured] => 
             [modifiedDate] => 1448293975
             [createDate] => 1448293975
           )

          [1] => Array
           (
             [id] => 266
             [imageName] => Apples in season.png
             [imagePath] => http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png
             [visible] => 1
             [featured] => 
             [modifiedDate] => 1448293975
             [createDate] => 1448293975
           )

        )
     )

My ajax

success: function(data){
    ...
    var thumbnails = {};
    $.each(data.productVariantImages,function(i, productVariantImages){
        thumbnails[data.sku] = this.imagePath;    
    });
    ...
 }       

Current output

{Apple SKU2: "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png"}

Desired output: Trying to iterate through and get key/value values as shown

{Apple SKU2: "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png",
 Apple SKU2: "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png"}

Upvotes: 0

Views: 56

Answers (1)

Yoram de Langen
Yoram de Langen

Reputation: 5499

It is not possible what you tried to achieve. An object item key should be unique at all times. Check this post.

The best solution for you would be an array with the images in it:

$.each(data.productVariantImages,function(key, val){ 
    thumbnails.push(val.imagePath);
});

getting a single image

var imageOne = thumbnails[0];

loop through the images

for(var thumb in thumbnails) {
// do stuff
}

Upvotes: 1

Related Questions