2014-01-19 28 views
0

我正試圖在標籤下獲取微笑數組然後屬性。我已經嘗試過搜索和簡單選擇。每一次嘗試都會導致一個未定義的變量。如果你能解釋如何選擇一個非常好的微笑陣列!如何在多級數組中選擇對象

{ 
     "status": "success", 
     "photos": [{ 
      "url": "http://tinyurl.com/673cksr", 
      "pid": "[email protected]_3547b9aba738e", 
      "width": 375, 
      "height": 406, 
      "tags": [{ 
       "uids": [], 
       "label": null, 
       "confirmed": false, 
       "manual": false, 
       "width": 30.67, 
       "height": 28.33, 
       "yaw": -16, 
       "roll": -1, 
       "pitch": 0, 
       "attributes": { 
        "face": { 
         "value": "true", 
         "confidence": 84 
        }, 
        "smiling": { 
         "value": "false", 
         "confidence": 46 
        } 
       }, 
       "points": null, 
       "similarities": null, 
       "tid": "[email protected]_3547b9aba738e_56.80_41.13_0_1", 
       "recognizable": true, 
       "center": { 
        "x": 56.8, 
        "y": 41.13 
       }, 
       "eye_left": { 
        "x": 66.67, 
        "y": 35.71, 
        "confidence": 51, 
        "id": 449 
       }, 
       "eye_right": { 
        "x": 50.67, 
        "y": 35.47, 
        "confidence": 57, 
        "id": 450 
       }, 
       "mouth_center": { 
        "x": 60.8, 
        "y": 51.23, 
        "confidence": 53, 
        "id": 615 
       }, 
       "nose": { 
        "x": 62.4, 
        "y": 42.61, 
        "confidence": 54, 
        "id": 403 
       } 
      }] 
     }], 
     "usage": { 
      "used": 21, 
      "remaining": 79, 
      "limit": 100, 
      "reset_time": 1390111833, 
      "reset_time_text": "Sun, 19 January 2014 06:10:33 +0000" 
     }, 
     "operation_id": "edc2f994cd8c4f45b3bc5632fdb27824" 
    } 
+0

'smiling'是一個對象不是數組對象。 – thefourtheye

+0

我的錯誤,編輯標題反映了這一點。 –

回答

1
JSON.parse(json).photos[0].tags[0].attributes.smiling 
1
obj.photos[0].tags[0].attributes.smiling 

最好的辦法是遍歷標籤,而不是在那裏

obj.photos.forEach(function(photo){ 
    photo.tags.forEach(function(tag){ 
    tag.attributes.smiling; // here it is 
    }); 
}); 
2

這個特殊的代碼硬編碼0,將聚集來自給定的所有smiling屬性對象並將其作爲數組返回。

  • map功能將得到來自各個smiling屬性,每一個標籤

  • concat功能將壓扁的所有屬性,並返回每張照片的單個陣列。

  • reduce功能將收集所有屬性的所有照片和result積累的結果,將在年底返回。


var result = data.photos.reduce(function(result, currentPhoto) { 
    return result.concat(currentPhoto.tags.map(function(currentTag) { 
     return currentTag.attributes.smiling; 
    })); 
}, []); 

console.log(result); 

輸出

[ { value: 'false', confidence: 46 } ] 
+0

得愛情JS「blackmagic」:) – pocesar

+0

@pocesar這是JavaScript的功能魔術:) – thefourtheye

1

這有點棘手,因爲你的JSON對象是對象和數組的混合物,但這裏是你如何去「微笑」對象(這是一個對象,因爲JavaScript中沒有關聯數組):

var smiling_object = obj["photos"][0]["tags"][0]["attributes"]["smiling"]; 

然後你,如果你想用它做什麼:

var some_var = smiling_object["value"]; 
var some_other_var = smiling_object["confidence"]; 

alert("The combined string is " + some_var + " and " + some_other_var);