R
R
Rektalizer2021-10-05 16:56:53
JavaScript
Rektalizer, 2021-10-05 16:56:53

How to return an object value from an array of class instances?

In the service of my module, there is a public method getQuizRepresentation () of the interface type, which contains the values ​​that are passed for display in the components. Some of the values ​​are inside the class array with which questions are generated. How can I pass the questionText value of the first question in the array to the getQuizRepresentation() method?

public results =
    [
      new ResultClass("Very bad", 0),             //где строка это resultText а число это worth
      new ResultClass("Below average", 30),
      new ResultClass("Average", 50),
      new ResultClass("Very good", 70),
      new ResultClass("Perfect", 100)
    ];

  public questions =
    [
      new QuestionClass("50 + 50",                 //строка это questionText
        [                                                              //это массив answers[]
          new AnswerClass("0", 0),                        // тут строка это answerText, а число это worth
          new AnswerClass("40", 0),
          new AnswerClass("80", 0),
          new AnswerClass("100", 100)
        ]),
      new QuestionClass("Which animal says meow?",
        [
          new AnswerClass("cat", 100),
          new AnswerClass("dog", 0),
          new AnswerClass("duck", 0),
          new AnswerClass("human", 50)
        ]),
    ];

  private quiz = new QuizClass(this.questions, this.results)

  private countQuestions() {
    let totalQuestionsCount: number = this.questions.length;
    return totalQuestionsCount;
  }

  public getQuizRepresentation(): QuizRepresentationInterface {
    return {
      questionText: '',
      answerTexts: [],
      isFinished: false,
      currentQuestionIndex: 0,
      totalQuestionsCount: this.countQuestions(),
      score: 0,
      resultText: ''
    };
  }


That is, let's say I need to pass to questionText: '', not an empty string, but the questionText value of the first element in the questions array, that is, '50+50'

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2021-10-05
@bingo347

If I understand correctly, then:this.questions[0].questionText

S
Sleeper_king_of_bones, 2021-10-15
@Sleeper_king_of_bones

public getQuizRepresentation(questions: QuestionClass[]): QuizRepresentationInterface {
   const questionText = questions[0].questionText; // тут не забыть проверку на пустоту.
    return {
      questionText,
      answerTexts: [],
      isFinished: false,
      currentQuestionIndex: 0,
      totalQuestionsCount: this.countQuestions(),
      score: 0,
      resultText: ''
    };
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question