2014-09-04 83 views
0

我有這個JSON響應...jQuery的JSON響應迭代與條件

{ 
"albums": { 
    "data": [ 
    { 
     "created_time": "2011-12-29T11:29:03+0000", 
     "id": "10150573478667193", 
     "name": "Timeline Photos", 
     "photos": { 
      "data": [ 
       { 
       "created_time": "2014-09-04T06:45:15+0000", 
       "source": "https://link.jpg", 
       "id": "10152743142372193", 
       "likes": { 
        "data": [ 
         { 
          "id": "10202250935623343", 
          "name": "Name LastName" 
         } 
        ], 
        "summary": { 
         "total_count": 13 
        } 
       } 
       } 
      ] 
     } 
    } 
    ] 
    } 
} 
} 

實際響應有很多更專輯對象和照片對象,但我縮短它顯示...現在我想做要做的是迭代通過響應,並獲得具有最高total_count(最喜歡的照片)在一些albums.I照片的「源」鏈接。我設法得到最高的total_count,但我無法得到「源」鏈接。這裏是我如何得到最高total_count-

var array=[]; 
$.each(response.albums.data,function(index,obj){ 
      //console.log("index1:" + index + " object1:" +obj); 
      $.each(obj,function(index2,obj2){ 
      //console.log("index2:" + index2 + " object2:" +obj2); 
      if(typeof obj2 == 'object'){ 
       $.each(obj2.data,function(index3,obj3){ 
       //console.log("index3:" + index3 + " object3:" +obj3); 
         $.each(obj3,function(index4,obj4){ 
         //console.log("index4:" + index4 + " object4:" +obj4); 
          if(typeof obj4 == 'object'){ 
           $.each(obj4,function(index5,obj5){ 
           //console.log("index5:" + index5 + " object5:" +obj5); 
            if(index5 == 'summary'){ 
             $.each(obj5,function(index6,obj6){ 
              //console.log("index6:" + index6 + " object6:" +obj6); 
              array[array.length] = obj6; 



             }); 

            } 
           }); 
          } 
         });   
       }); 
      } 
      }); 
     }); 
     var mostLikedNumber=Math.max.apply(Math,array); 
     console.log("Most liked - " +mostLikedNumber); 

任何幫助表示讚賞!

+0

我可以使用'jQuery.parseJSON()'訪問對象的數據看不到? - http://api.jquery.com/jquery.parsejson/ – Kolors 2014-09-04 23:19:39

+0

它是我第一次解析json,我做了這樣的沒有這個功能,我得到了我的數量,但其餘的我不能這樣做。 – Shile 2014-09-04 23:21:45

+0

爲什麼不使用jQuery,它是爲此目的而設計的,因爲您已經將其與其他函數一起使用,看起來有點像爲自己創建工作,無緣無故... – Kolors 2014-09-04 23:23:23

回答

4

看來你的腳本是過於複雜:

var mostLikes = -1; 
var mostLiked = []; 

$.each(response.albums.data, function (idx, album) { 
    $.each(album.photos.data, function (idx, photo) { 
     if (photo.likes.summary.total_count > mostLikes) { 
      mostLikes = photo.likes.summary.total_count; 
      mostLiked = [photo.source]; 
     } else if (photo.likes.summary.total_count == mostLikes) { 
      mostLiked.push(photo.source); 
     } 
    }); 
}); 

console.log("Most liked - " + mostLiked.join(",") + " = " + mostLikes); 

這說明了關係也是如此。

演示:http://jsfiddle.net/jtbowden/dc84k3x0/

+0

我試過了你的代碼,但是如果條件有錯誤 - 「photo.likes未定義」。 – Shile 2014-09-05 01:48:16

+0

我剛剛添加如果(typeof photo.likes!='undefined'){}在現有的條件下,它現在正在工作...它發生,因爲有些照片沒有喜歡,所以他們undefined.Anyways非常感謝! – Shile 2014-09-05 02:04:05