How to get loop throw and structure data.
loop throw questions array and get comments with respect of the questionId
and replies with respect of commentId
Example
let data = {
questions: [
{
questionId: 1,
questionText: "Question 1",
},
{
questionId: 2,
questionText: "Question 2",
},
{
questionId: 3,
questionText: "Question 3",
},
{
questionId: 4,
questionText: "Question 4",
},
],
comments: [
{
commentId: 1,
questionId: 1,
commentText: "Comment 1",
},
{
commentId: 2,
questionId: 1,
commentText: "Comment 2",
},
{
commentId: 3,
questionId: 1,
commentText: "Comment 3",
},
{
commentId: 4,
questionId: 3,
commentText: "Comment 4",
},
{
commentId: 5,
questionId: 2,
commentText: "Comment 5",
},
],
replies: [
{
commentId: 1,
replyId: 1,
replyText: "Reply 1",
},
{
commentId: 2,
replyId: 2,
replyText: "Reply 2",
},
{
commentId: 3,
replyId: 3,
replyText: "Reply 3",
},
{
commentId: 3,
replyId: 4,
replyText: "Reply 4",
},
{
commentId: 5,
replyId: 5,
replyText: "Reply 5",
},
],
};
Try yourself to prepare interview if stuck blow is the solution
Desire output:
[
{
questions: { questionId: 1, questionText: 'Question 1' },
comments: { commentId: 1, questionId: 1, commentText: 'Comment 1' },
replies: [ [Object] ]
},
{
questions: { questionId: 1, questionText: 'Question 1' },
comments: { commentId: 2, questionId: 1, commentText: 'Comment 2' },
replies: [ [Object] ]
},
{
questions: { questionId: 1, questionText: 'Question 1' },
comments: { commentId: 3, questionId: 1, commentText: 'Comment 3' },
replies: [ [Object], [Object] ]
},
{
questions: { questionId: 2, questionText: 'Question 2' },
comments: { commentId: 5, questionId: 2, commentText: 'Comment 5' },
replies: [ [Object] ]
},
{
questions: { questionId: 3, questionText: 'Question 3' },
comments: { commentId: 4, questionId: 3, commentText: 'Comment 4' },
replies: []
}
]
Solution π π π
function generateOutput(data) {
const { questions, comments, replies } = data;
// CODE HERE
let output = [];
questions.map((i)=>{
comments.map((c)=>{
const reply = replies.filter((r)=>r.commentId===c.commentId)
if(c.questionId===i.questionId){
output.push({questions:i,comments:c,replies:reply})
}
})
})
return output;
}
let output = generateOutput(data);
console.log(output);
Thanks for reading, if it is helpful comment blow with Thanks π
Top comments (0)