Marco V
Marco V

Reputation: 2623

Add item to every object in array with JavaScript

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

Answers (4)

Michał Perłakowski
Michał Perłakowski

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

mzdv
mzdv

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

BenG
BenG

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

Roko C. Buljan
Roko C. Buljan

Reputation: 206078

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

https://jsfiddle.net/o0pa4z0w/

Upvotes: 2

Related Questions