我试图获取从 jquery ajax 调用返回的一些特定数据,数据对象数组如下所示:
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 开发工具控制台,这就是数组的样子
console.log(data); // shows me the array
console.log(data.Key); //undefined
console.log(data[0].Key); // blows up
最佳答案
让我们更加小心一点,这样您的代码就不会崩溃。
首先,您可以过滤 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);
}
}
关于javascript - 遍历 Javascript 对象搜索键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33489929/