2015-11-03 38 views
0

我想從jQuery的AJAX調用回來一一些具體的數據和數據對象數組看起來像這樣:我是遍歷通過JavaScript對象尋找鍵值

Object {Version: Object, Content: null, StatusCode: 200, ReasonPhrase: "OK", Headers: Array[1]…} 

的特定部位興趣是

Headers --> Object -->Key "FORCE_REDIRECT" (FORCE_REDIRECT I wish to find and test if it exists) 

然後我想用

Value --> 0 --> "Grid.html"  (Grid.html is where i plan to redirect to) 

Chrome開發工具的控制檯,這是該數組樣子

enter image description here

console.log(data); // shows me the array 
console.log(data.Key); //undefined 
console.log(data[0].Key); // blows up 
+0

您錯過了'Headers'屬性。嘗試'console.log(data.Headers [0] .Key);' – Griffith

回答

1

讓我們繼續謹慎一點,所以你的代碼不能炸燬。

首先,你可以過濾Headers陣列包含具有右鍵只有對象:

if(!data.Headers){ 
    //fail 
    return; 
} 
var headers = data.Headers.filter(function(o){return o.Key && o.Key==="FORCE_REDIRECT";}); 

佔據第一位:

var headerObj = headers[0]; 

確保它不爲空:

if(headerObj) //if it exists... 
{ 
    var aValue = headerObj.Value[0]; //take the first value 
    if(aValue) //if it exists... 
    { 
     doSomethingWith(aValue); 
    } 
} 
1

你當試圖訪問你的data對象錯過了一個屬性(Headers):

console.log(data); 
console.log(data.Headers[0].Key); //"FORCE_REDIRECT" 
console.log(data.Headers[0].Value[0]); //"Grid.html"