0

If I have something like this:

var quiz = [{
    "questionID": "KC2Q4",
    "correctAnswer": "KC2Q4a"
},{
    "questionID": "KC2Q5",
    "correctAnswer": "KC2Q5b" 
}];

and have a variable that we can call "question" that has a value of a string like KC2Q4. How do I return the "correctAnswer" for the "questionID" that matches the variable "question" in a new variable "answer"?

  • 2
    This [SO question](http://stackoverflow.com/questions/7364150/find-object-by-id-in-array-of-javascript-objects) is what you are looking for. – The_Black_Smurf Jan 06 '15 at 22:07
  • Yes, this is exactly what I was looking for! Thank you. That post didn't come up in my search before I posted. :/ – Jonathan Bruch Jan 06 '15 at 22:24

2 Answers2

2

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];
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
2

You essentially want to iterate over your array, checking each object for the proper questionID. When you find that object, return the correctAnswer property of that object.

var question = "KC2Q4";
for( var i=0; i<quiz.length; i++ ){
  if( quiz[i].questionID === question ){
    return quiz[i].correctAnswer;
  }
}
Liam Schauerman
  • 851
  • 5
  • 10