0

I am trying to display an array within another array and I am not sure how.

Here is my code:

interface QuestionHeader {
  id: number;
  questionName: string;
  question: Question;
}

interface Question {
  id: number;
  questionContent: string;
  isSelected: false;
}

export default function Questions()  {
  
  const [questions, setQuestions] = useState<QuestionHeader[]>([]);
  useEffect(() =>  {
    const requestOptions = {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' }
    };
    fetch(`URL`, requestOptions)
    .then(res => res.json())
    .then(e => {
      setQuestions(e)
    });
  },[])
  return (
    <div style={{ textAlign: "center" }}>
          <div>
            <ul>
              {questions.map(item=>{
                return (<li>{item.questionName}{item.question.map(q=> )}</li>
                );
                
              })}
            </ul>
...

When I try to do item.map or item.question.map, I get an error that map does not exist in type Question.

3
  • As you define the key question on QuestionHeader it is not an array so you cannot iterate over it. If you can provide an response example I could give you extra help. Commented Jan 6, 2021 at 3:48
  • 1
    response:[ { "id": 1, "questionID": 1, "questionName": "NPS", "question": [] }, { "id": 2, "questionID": 2, "questionName": "Customer Satisfaction", "question": [ { "questionID": 2, "questionContent": "brand satisfaction" } ] } ] Commented Jan 6, 2021 at 3:56
  • you have to declare var index inside the map function (item, index) to fetch array and iterate array. Commented Jan 6, 2021 at 8:06

2 Answers 2

1

Consider changing the QuestionHeader interface to:

interface QuestionHeader {
  id: number;
  questionName: string;
  question: Question[];
}
Sign up to request clarification or add additional context in comments.

Comments

0

try below code

let list_data = [ { "id": 1, "questionID": 1, "questionName": "NPS", 
   "question": [] }, { "id": 2, "questionID": 2, "questionName": "Customer 
    Satisfaction", "question": [ { "questionID": 2, "questionContent": "brand 
    satisfaction" } ] } ] ;

renderListData() {
  return list_data.map((item,i) => <div>
    <label>{item['questionName']}</label>
   <div>{this.renderQuestions(item['question'])}</div>
  </div>)
  }

 renderQuestions(list_que) {
     if(list_que.length > 0) {
       return list_que.map((item,i) => <div>
      <label>{item['questionContent']}</label>
    </div>)
    }
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.