Попытка ссылаться на несколько элементов из массива, который находится внутри объекта - PullRequest
0 голосов
/ 15 декабря 2018

У меня есть этот объект, который имеет массив с несколькими объектами и массивами.Я пытался выяснить, как ссылаться на несколько элементов одновременно, но не могу найти способ.

  var questions =  {
  options : [{
  question : "Only one province is oficially bilingual, can you guess which 
  one?",
  choices : ["Quebec", "British Columbia", "Manitoba", "Newbrunswick"],
  answer : 3
  },

  {  question : "Which canadian city is considered The Hollywood North?",
  choices : ["Manitoba", "Vancouver", "Beamsville", "Niagara Falls",],
  answer : 1
  },

  {  question : "What is the capital of Canada?",
  choices : ["Ottawa", "Toronto", "Vancouver", "Edmonton"],
  answer : 0
  },

  {  question : "What are the official winter and summer sports of Canada?",
  choices : ["Ice hockey and lacrosse", "Boxing and Baseball", "Skiing and 
  Swimming", "Football and Tennis"],
  answer : 0
  },

  {  question : "How many time zones does Canada Have?",
  choices : ["4", "3", "5", "6"],
  answer : 3
  },

  {  question : "What animal is on the Canadian quarter?",
  choices : ["Whale", "Polar Bear", "Caribou", "Beaver"],
  answer : 2
  },

  {  question : "What is the Canadian $1 coin called?",
  choices : ["Moonie", "Dolly", "Loonie", "Toonie"],
  answer : 2
  },

  {  question : "What is the leader of Canada called?",
  choices : ["Queen", "Prime Minister", "King", "President"],
  answer : 1
  },

  {  question : "What is the name of the highest mountain in Canada?",
   choices : ["Mount Logan", "Mount Carleton", "Mount Saint Elias", "Mount 
  Columbia"],
  answer : 0
  }
  ]};

Я пытался:

   console.log(questions.options[0].question);
   console.log(questions.options[1].question);
   console.log(questions.options[2].question);  
   //etc...

Можно ли как-нибудь отобразить все вопросы из одного console.log?Я предполагаю, что цикл for сделает это, но я не могу понять.Заранее большое спасибо.

1 Ответ

0 голосов
/ 15 декабря 2018

вы можете сделать что-то вроде:

questions.options.forEach(function(item) {
    console.log(question.question);
});

или если вам нужна только одна строка, которая относится ко всем элементам:

var allQuestions = questions.options.reduce(function(all, current) { 
    return all + ' - ' + current;
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...