0

I have an object like so:

answers = {
   "q1" :  {
        "selected": "a",
        "correct": "b"
        },
   "q2": {
        "selected": "c",
        "correct": "d"
       },
    etc...
}

how do I compare selected and correct?

i'm trying

for (let key in answers) {
    if (key.selected === key.correct) {
        correct++;
    } else {
        incorrect++;
    }
}

but it doesn't work. I keep getting all questions marked correct. Pretty sure I need to do something else to go down a level in the object but not sure how to do it.

if I do answers[key].selected === answers[key].correct all come out as incorrect

3

3 Answers 3

1

Well... you're comparing the keys and not the values, where selected and correct will be undefined for both cases thus correct. You probably meant:

if (answers[key].selected === answers[key].correct) {
Sign up to request clarification or add additional context in comments.

4 Comments

Should we answer this or close it as duplicate? There are probably at least 10 questions about for( key in object )
this results in all my answers coming up as incorrect even though their values match in the answers object. any ideas if I have anything else wrong?
@Vidro3: WRT answers[key].selected === answers[key].correct Look at your data. In none of the objects is the .selected property the same as the .correct property. We don't know what you actually need because you haven't posted a complete yet minimal demo with a description of what the behavior should be beyond what you've shown.
@squint ahh crud you are correct. some of my values are strings and others are int. Have to see how that happened. Thanks
0

You want:

for (let key in answers) {
  if (answers[key]["selected"] === answers[key]["correct"]) {
    correct++; 
  } else {
    incorrect++; 
  }
}

1 Comment

answers.key.selected won't give the desired property, and you removed the variable let declaration for some reason.
0

you need to use it like this

answers = {
   "q1" :  {
        "selected": "a",
        "correct": "b"
        },
   "q2": {
        "selected": "c",
        "correct": "c"
       }

};
var correct=0;incorrect=0;
for (let key in answers) {
 
 if (answers[key].selected === answers[key].correct)
 {
   correct++;
 }
else
{
   incorrect++;
}
}
   console.log(correct);
   console.log(incorrect);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.