ReactJS Iteration over a an Array

i made this list below of four different paragraph that gets its value from a nested Array that iterates over values of option[0} option [1] …ect , i want to re-write this code using the map method it will be in one line , appreciate your help

<div className="question-option">
        <p>{QuestionsList[0].options[0]}</p>
        <p>{QuestionsList[0].options[1]}</p>
        <p>{QuestionsList[0].options[2]}</p>
        <p>{QuestionsList[0].options[3]}</p>
      </div>

@freesudani ,

you can create a single <p> tag and call your map method inside it.

QuestionsList.map((item) =>{
return <p>{item}</p> 
})

You can do something like this

1 Like

I got an Array with nested objects an Arrays , so i want to iterate over them using the logic in the code above this will not work for me :slight_smile:

The above logic demonstrates how you might start. You have an array of questions and within each question it seems you have an array of options. So you might need to create a map…within a map.

Hopefully nobody here will write your code for you, you won’t learn anything I’d they do. But @nivethakrishnan72 gave you some great guidance.

2 Likes

@freesudani

You can flatten your array first and iterate through it. I hope the below link will help you.

1 Like

@nivethakrishnan72 @snowmonkey thank you guys, appreciate the feedback.

Suppose we had a list of questions. We might start with

<QuestionsList questions={questionsList} />

But within that component, we want to work with individual questions - maybe with a Question component:

{ questions.map( (question, index) =>{
  return <Question question={question} />
}) }

But within that question, you have an optionsList, which might be handled in much the same way.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.