You should use Array.prototype.filter
function (note filter()
is a ECMA-Script 5.x native function: you don't need third-party libraries or frameworks!!):
var correctAnswer = "KC2Q4a";
// "filter" is like a "where". It iterates each object in your array
// and returns ones that fit the given condition as a closure:
var answersFound = quiz.filter(function(question) {
return question.correctAnswer == correctAnswer;
});
// You could verify if length > 0, but you want to be sure that
// there's only a single match for a given correct answer, because I feel
// that "correctAnswer" is like an unique id...
if(answersFound.length == 1) {
// Since there's a found answer to given "correctAnswer",
// you get the single result (i.e. the question object):
var answer = answersFound[0];
}
If you find above checking useless (in my case, I would call it defensive programming), you may retrieve the question object directly this way:
// Without the checking done in the other code listing, you've two risks:
// a. "quiz" could contain no question objects and the filter will return zero results
// meaning that getting first result array index will throw an error!
//
// b. "quiz" could contain question objects but what you're looking for isn't
// present in the so-called array. Error too!
var answer = quiz.filter(function(question) {
return question.correctAnswer == correctAnswer;
})[0];