1

I am making a kind of Trivial Pursuit game. I have the thousands of questions and answers; see example below:

var trivialPursuitCards = [
   {
    question: "What nationality was Chopin?",
    answer: ["American", "Polish", "German", "Czech"],
    difficulty: 2
   }, 
   {
    question: "Who cut Van Gogh's ear?",
    answer: ["His sister", "His brother", "Himself", "He was born that way"],
    difficulty: 2
   }
];

Now I just need to add one more property to each card namely: rightAnswer: undefined.

What is the best way to get this done for all the cards?

1
  • 3
    Non-existing properties are undefined by default so it seems unlikely that you'd need to set it explicitly. Commented May 21, 2016 at 13:00

4 Answers 4

2
for(var i=0; i<trivialPursuitCards.length; i++) {
    trivialPursuitCards[i].rightAnswer = undefined;
}

https://jsfiddle.net/o0pa4z0w/

Sign up to request clarification or add additional context in comments.

Comments

1

use map then add your property:-

var trivialPursuitCards = [{
  question: "What nationality was Chopin?",
  answer: ["American", "Polish", "German", "Czech"],
  difficulty: 2
}, {
  question: "Who cut Van Gogh's ear?",
  answer: ["His sister", "His brother", "Himself", "He was born that way"],
  difficulty: 2
}];

var update = trivialPursuitCards.map(function(e, i) {
  e.rightAnswer = undefined;
  return e;
});

console.log(update);

Comments

0

trivialPursuitCards.map(function (card) { card.rightAnswer = null; });

Because it's better to add a null than undefined since the rightAnswer should exist, but currently isn't set.

Comments

0

As pointed out by Juhana:

Non-existing properties are undefined by default so it seems unlikely that you'd need to set it explicitly.

However, if you really want to do this, you can use Array.prototype.map():

trivialPursuitCards = trivialPursuitCards.map(element=>
  element.rightAnswer = undefined
)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.