Reputation: 2623
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?
Upvotes: 1
Views: 85
Reputation: 92511
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
)
Upvotes: 0
Reputation: 827
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.
Upvotes: 0
Reputation: 15154
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);
Upvotes: 1
Reputation: 206078
for(var i=0; i<trivialPursuitCards.length; i++) {
trivialPursuitCards[i].rightAnswer = undefined;
}
https://jsfiddle.net/o0pa4z0w/
Upvotes: 2