Hi I am trying to solve a problem. Initially I am getting data from an API like so
{
"questions":[
{
"id":1,
"questionHeader":"Some question header",
"questionText":"Some question text?",
},
{
"id":2,
"questionHeader":"Some question header",
"questionText":"Some question text?",
},
],
"answers":[
{
"id":1,
"questionId":1,
"answer":"Some answer",
},
{
"id":2,
"questionId":1,
"answer":"Some answer",
},
{
"id":3,
"questionId":2,
"answer":"Some answer",
},
],
"answerText":[
{
"id":1,
"answerId":1,
"text":"Some text",
},
{
"id":2,
"answerId":2,
"text":"Some text",
},
{
"id":3,
"answerId":3,
"text":"Some text",
},
]
}
What I was initially after was to get the answers embedded within their respective question based on a questions id and an answers questionId. So for the above, I am trying to achieve something like the following.
{
"questions":[
{
"id":1,
"questionHeader":"Some question header",
"questionText":"Some question text?",
"answers":[
{
"id":1,
"questionId":1,
"answer":"Some answer",
},
{
"id":2,
"questionId":1,
"answer":"Some answer",
},
]
},
{
"id":2,
"questionHeader":"Some question header",
"questionText":"Some question text?",
"answers":[
{
"id":3,
"questionId":2,
"answer":"Some answer",
},
]
},
],
}
This was achieved by doing
const newItem = data.questions.map((t1) => ({
...t1,
answers: data.answers.filter((t2) => t2.questionId === t1.id),
}));
However, I now need to get the answerText embedded within the answers based on the id. So the overall format should be
{
"questions":[
{
"id":1,
"questionHeader":"Some question header",
"questionText":"Some question text?",
"answers":[
{
"id":1,
"questionId":1,
"answer":"Some answer",
"answerText":[
{
"id":1,
"answerId":1,
"text":"Some text",
},
]
},
{
"id":2,
"questionId":1,
"answer":"Some answer",
"answerText":[
{
"id":2,
"answerId":2,
"text":"Some text",
},
]
},
]
},
{
"id":2,
"questionHeader":"Some question header",
"questionText":"Some question text?",
"answers":[
{
"id":3,
"questionId":2,
"answer":"Some answer",
"answerText":[
{
"id":3,
"answerId":3,
"text":"Some text",
},
]
},
]
},
],
}
How can this be achieved? Thanks