2

I have an array of objects ("array"), each containing other arrays of objects.

[
  {
     name: "Object 1",
     question: [{value: "This", type: "text"}, {value: "is", type: "text"},  {value: "1", type: "number".]
     answer: [{value: "Answer", type: "text"}, {value: "is", type: "text"},  {value: "1", type: "number".]
  },
  {
     name: "Object 2",
     question: [{value: "This", type: "text"}, {value: "is", type: "text"},  {value: "2", type: "number".]
     answer: [{value: "Answer", type: "text"}, {value: "is", type: "text"},  {value: "2", type: "number".]
  },
]

In React, I'd like to render out the below:

<Typography>This</Typography><Typography>is</Typography><Number>1</Number>
<Typography>Answer</Typography><Typography>is</Typography><Number>1</Number
<Typography>This</Typography><Typography>is</Typography><Number>2</Number>
<Typography>Answer</Typography><Typography>is</Typography><Number>2</Number

I have tried the below, but can't work out why some of it won't map correctly.

array.map(snippet => {
 snippet.question.map(question => {
  return something here;
})

EDITED AS FORGOT A LEVEL OF OBJECTS

0

1 Answer 1

1

Try some thing like this.

array.map(snippet => (
  <>
    {snippet.question.map(que => {
      if (que.type === "text") {
        return <Typography>{que.value}</Typography>;
      } else if (que.type === "number") {
        return <Number>{que.value}</Number>;
      }
      return null;
    })}
    {snippet.answer.map(ans => {
      if (ans.type === "text") {
        return <Typography>{ans.value}</Typography>;
      } else if (ans.type === "number") {
        return <Number>{ans.value}</Number>;
      }
      return null;
    })}
  </>
));
Sign up to request clarification or add additional context in comments.

1 Comment

Apologies, I had a mistake in the question so have edited it. Apologies.

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.