简体   繁体   中英

Access nested array items in javascript

I'm using the javascript trivia API to make an application. I'm having issues displaying each of the values of the wrong answer.

So far I have saved them in my state, along with the questions, and the correct answer

componentDidMount() {
  axios.get('https://opentdb.com/api.php?amount=50').then(response => {
    for (var key in response.data.results) {
      console.log(response.data.results[key].question)
      this.setState(prevState => ({
        questions: [...prevState.questions, response.data.results[key].question],
        answers: [...prevState.answers, response.data.results[key].correct_answer],
        wrongAnswers: [...prevState.wrongAnswers, response.data.results[key].incorrect_answers]

      }));
    }
  });
}

this works fine, but my issue is that the wrong answers is an array itself, so whenever I display the state

<p>{this.state.wrongAnswers[this.state.random]}</p> // prints array of strings

I get another array, and I can access each element using the dot operator, because I don't know the answers since the questions are chosen randomly.

I want to display the values dynamically using radio buttons. Is there a way to access each element of the nested array and display them dynamically?

You can loop through that array and show the wrong answers

{Array.isArray(this.state.wrongAnswers) && this.state.wrongAnswers.map((wrongAnswer, index) => {
  <p key={'Key-'+index}>wrongAnswer}</p>
}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM