Correct syntax of printing array objects inside array React

Tags: , ,



I’m new to ReactJS library, and I’m trying to print the following structure of array:

Main Array[
  Array0[
     Object0{
      questions: "question1",
      answer1: "answer1",
      answer2: "answer2"
     },
     Object1{
      questions: "question1",
      answer1: "answer1",
      answer2: "answer2"
     }
  ]
]

This structure of array is hold in state called question, I have tried to create new functional component and print it on user screen but I received the following error:

TypeError: quest[0].map is not a function

My target is to print Object0 and Object1 data.

const [question, setQuestion] = useState([]);
setQuestion([
  [
      {
       questions: "question1",
       answer1: "answer1",
       answer2: "answer2"
      },
      {
       questions: "question2",
       answer1: "answer1",
       answer2: "answer2"
      }
  ]
]);
//Component
const QuestionsComponent = function questions(){
    return (
        <div>
            {
                question.map(function (quest){
                    quest[0].map(function(ques){
                        return quest.questions;
                    })
                })
            }
        </div>
    );
}


 return(
   <>
    <QuestionsComponent />
   </>
 );

What is the correct approach to print array of objects inside of array?

Answer

When you map over question:

question.map(function (quest){

The quest variable will be each element of that array. Which in this case that element is:

[
  {
   questions: "question1",
   answer1: "answer1",
   answer2: "answer2"
  },
  {
   questions: "question2",
   answer1: "answer1",
   answer2: "answer2"
  }
]

An array of objects. So referencing an element of that array (such as quest[0]) would be:

{
   questions: "question1",
   answer1: "answer1",
   answer2: "answer2"
}

Which indeed isn’t an array and has no .map().

It sounds like you wanted to map over quest, not an element of it:

quest.map(function(ques){
    return quest.questions;
})

Ultimately it looks like your variable naming is confusing you here. You have something called question which contains an array, each of which contains an array, each of which contains a property called questions. The plurality/singularity of those is dizzying.

Perhaps question should really be questionGroups? It’s an array of arrays. Each “group” is an array of questions. Each of which should have a property called question.

Variable naming is important, and helps prevent confusion when writing your own code. So in this case it might be something like:

const [questionGroups, setQuestionGroups] = useState([]);

// then later...
questionGroups.map(function (questionGroup){
    questionGroup.map(function (question){
        return question.question;
    })
})


Source: stackoverflow