Reputation:
I have the following object:
var myObj =
{"qId":"726112",
"text":"xx",
"answers":[{"answerId":null,
"answerUId":1,
"text":"xx",
"correct":null,
"response":false},
{"answerId":null,
"answerUId":2,
"text":"xx",
"correct":null,
"response":false},
{"answerId":null,
"answerUId":4,
"text":"xx",
"correct":null,
"response":false}]}
Can someone tell me how I can use an if statement to check if any one of the response fields has a value of true?
Upvotes: 1
Views: 73
Reputation: 95
If you want to find is it true or false change status of response in Array . you can easily understood.
var myObj = {"qId":"726112",
"text":"xx",
"answers": [{"answerId":null, "answerUId":1, "text":"xx", "correct":null, "response":true},
{"answerId":null,
"answerUId":2,
"text":"xx",
"correct":null,
"response":false},
{"answerId":null,
"answerUId":4,
"text":"xx",
"correct":null,
"response":true}]
};
if(myObj.answers.length > 0){
for (var i in myObj.answers){
if(myObj.answers[i].response){
console.log(i+"th index of answers Array in myObj object has "+myObj.answers[i].response);
}
else{
console.log(i+"th index of answers Array in myObj object has "+myObj.answers[i].response);
}
}
}
output :
0th index of answers Array in myObj object has true
1th index of answers Array in myObj object has false
2th index of answers Array in myObj object has true
Upvotes: -1
Reputation: 239443
You can use Array.prototype.some
function, which returns true
if atleast one of the elements return true
, like this
if (myObj.answers.some(function(answer) { return answer.response; })) {
# Atleast one of them is true
}
Upvotes: 3