2017-04-12 86 views
1

我正在嘗試檢查從查詢返回的值。這個結果是JSON格式。我的代碼工作,直到我的條件聲明。
在調試過程中,我發現我的條件語句總是失敗,因爲我試圖從JSON檢索並比較的值始終未定義。無法從NodeJS中的JSON響應中獲取值

var promise = insertDataInMongo([body, token]); 
var newBody = JSON.parse(body); 

if (newBody.paging.facebookPost !== -1 || newBody.paging.youtube !== -1 || newBody.paging.twitter !== -1 || newBody.paging.facebook !== -1 || newBody.paging.reddit !== -1 || newBody.paging.youtubeComment !== -1 || newBody.paging.news !== -1) 
    promise.then(getAthleteMedia([athlete, token, newBody.paging.facebook, newBody.paging.facebookPost, newBody.paging.reddit, newBody.paging.youtube, newBody.paging.youtubeComment, newBody.paging.twitter, newBody.paging.news])) 

被返回的身體看起來是這樣的:

{ "paging": [ 
{ 
    "youtubeComment": -1 
}, 
{ 
    "youtube": -1 
}, 
{ 
    "twitter": -1 
}, 
{ 
    "facebook": -1 
}, 
{ 
    "reddit": -1 
}, 
{ 
    "facebookPost": -1 
}, 
{ 
    "news": -1 
} 
]} 

當我調試,我看到以下內容:

JSON Values

然而,解析值顯示爲:

Parsed values

任何幫助,非常感謝。謝謝,

回答

1

你正在接收的是一個對象數組而不是對象對象,因此你應該首先使用索引訪問它們,然後訪問屬性。 假設JSON響應的格式總是相同的,這裏是工作的JSfiddle鏈接,下面是來自How to get index of object by its property in javascript的文章answer的啓發的示例代碼。

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");

+0

對不起..我失去了一些東西,怎麼是你貼比我原來有什麼不同? – SAS

+0

對不起,我錯過了更新索引,請重新檢查jsfiddle鏈接其更新爲https://jsfiddle.net/44fakLh7/1/ – warl0ck

+0

好吧..我懷疑是相同的,並嘗試了此前。但是我發現它,返回數組中的對象序列並不總是相同的。所以我不能硬編碼索引。 – SAS