Reputation: 13
I am trying to check the values returned from a query. This result is in JSON format. My code works, until my condition statement.
While debugging I found that my condition statement was always failing because the value I am trying to retrieve from JSON and compare is always undefined.
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]))
The body that gets returned looks like this:
{ "paging": [
{
"youtubeComment": -1
},
{
"youtube": -1
},
{
"twitter": -1
},
{
"facebook": -1
},
{
"reddit": -1
},
{
"facebookPost": -1
},
{
"news": -1
}
]}
When I debug, I see the following:
However, the parse values are showing as:
Any help is much appreciated. Thanks,
Upvotes: 1
Views: 263
Reputation: 3464
What you are receiving is an array of objects not the objects of objects, therefore you should access them with indexes first then the property. Assuming the format of the JSON response is always same here is the working JSfiddle link and below is the sample code inspired from this How to get index of object by its property in javascript post's 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");
Upvotes: 1