1

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?

  • cant get ur requirement, please clarify, what do u mean by check if any one of the response fields has a value of true – Nitin Varpe Mar 15 '14 at 12:08
  • The object has a property called answers which has an array of objects. If any of the response properties in those arrays has a value of true. That's what I need to know. –  Mar 15 '14 at 12:10

2 Answers2

3

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
}

Working demo

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
-1

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

  • http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea and formatting the code and output would be helpful. – Xotic750 Mar 15 '14 at 13:51