我正在尝试检查查询返回的值。此结果采用JSON格式。我的代码工作,直到我的条件语句。
在调试时我发现我的条件语句总是失败,因为我试图从JSON检索并比较的值总是未定义。
{ "paging": [
{
"youtubeComment": -1
},
{
"youtube": -1
},
{
"twitter": -1
},
{
"facebook": -1
},
{
"reddit": -1
},
{
"facebookPost": -1
},
{
"news": -1
}
]}
返回的主体看起来像这样:
{{1}}
当我调试时,我看到以下内容:
但是,解析值显示为:
非常感谢任何帮助。谢谢,
答案 0 :(得分:1)
您收到的是一个对象数组而不是对象的对象,因此您应首先使用索引访问它们,然后使用属性。 假设JSON响应的格式总是相同的是工作spell.py链接,下面是来自此JSfiddle帖子How to get index of object by its property in javascript的示例代码。
var newBody = {
"paging": [{
"youtubeComment": -1
}, {
"youtube": -1
}, {
"twitter": -1
}, {
"facebook": -1
}, {
"reddit": -1
}, {
"facebookPost": -1
}, {
"news": -1
}]
};
function check(array, attr, value) {
for (var i = 0; i < array.length; i += 1) {
if (array[i][attr] === value) {
return false;
}
}
return true;
}
function get_value(array, attr) {
for (var i = 0; i < array.length; i += 1) {
if (array[i].hasOwnProperty(attr)) {
return array[i][attr];
}
}
}
if (check(newBody.paging, "facebook", -1) || check(newBody.paging, "youtubeComment", -1) || check(newBody.paging, "youtube", -1) || check(newBody.paging, "twitter", -1) || check(newBody.paging, "reddit", -1) || check(newBody.paging, "facebookPost", -1) || check(newBody.paging, "news", -1)) {
// promise.then(getAthleteMedia([athlete, token, get_value(newBody.paging, "facebook"), ... get_value(newBody.paging, "news")]));
// similarly just pass the function in your promise, hope it clears how to get the values as well
console.log(get_value(newBody.paging, "facebook"));
} else console.log("not in if");