无法通过每个()获取数据

时间:2015-12-04 07:56:52

标签: jquery ajax for-loop

对不起,我还是很陌生。我在ajax成功中从这个数组中获取数据时遇到问题。我试图遍历productVariantImages以获得两个imagePath,但我只能得到一个来自id 496.下面是数组的示例。

如果可能的话,我想使用对象而不是数组

[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
           )

        )
     )

我的ajax

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

当前输出

{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",
 Apple SKU2: "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png"}

1 个答案:

答案 0 :(得分:1)

你试图实现的目标是不可能的。对象项键始终应该是唯一的。 Check this post

最适合您的解决方案是包含图像的数组:

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

获取单张图片

var imageOne = thumbnails[0];

循环播放图像

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