I’m getting this type of data from backend
let a = [
{
QuestionNo: "1",
pageNumber: "1",
response: "xyz",
question: "What is your Name",
publicUrl: null,
fieldtype: "Text"
},
{
QuestionNo: "2",
pageNumber: "1",
response: "7897897987",
question: "Phone no",
publicUrl: null,
fieldtype: "Phone"
},
{
QuestionNo: "1",
pageNumber: "2",
response: "true",
question: "Are you employeed?",
publicUrl: null,
fieldtype: "Checkbox"
},
{
QuestionNo: "2",
pageNumber: "2",
response: "2023-03-30T10:27:00.000Z",
question: "validity",
publicUrl: null,
fieldtype: "Datetime"
}
];
I need to convert it like this
[
{
"pageNumber": "1",
"Questions": [
{
QuestionNo: "1",
pageNumber: "1",
response: "xyz",
question: "What is your Name",
publicUrl: null,
fieldtype: "Text"
},
{
QuestionNo: "2",
pageNumber: "1",
response: "7897897987",
question: "Phone no",
publicUrl: null,
fieldtype: "Phone"
}
]
},
{
"pageNumber": "2",
"Questions": [
{
QuestionNo: "1",
pageNumber: "2",
response: "true",
question: "Are you employeed?",
publicUrl: null,
fieldtype: "Checkbox"
},
{
QuestionNo: "2",
pageNumber: "2",
response: "2023-03-30T10:27:00.000Z",
question: "validity",
publicUrl: null,
fieldtype: "Datetime"
}
]
}
]
My code
let finalAnswer = [];
let a = [
{
QuestionNo: "1",
pageNumber: "1",
response: "xyz",
question: "What is your Name",
publicUrl: null,
fieldtype: "Text"
},
{
QuestionNo: "2",
pageNumber: "1",
response: "7897897987",
question: "Phone no",
publicUrl: null,
fieldtype: "Phone"
},
{
QuestionNo: "1",
pageNumber: "2",
response: "true",
question: "Are you employeed?",
publicUrl: null,
fieldtype: "Checkbox"
},
{
QuestionNo: "2",
pageNumber: "2",
response: "2023-03-30T10:27:00.000Z",
question: "validity",
publicUrl: null,
fieldtype: "Datetime"
}
];
a.forEach((val) => {
if (finalAnswer.length > 0) {
finalAnswer.filter((v, i) => {
if (val.pageNumber === v.pageNumber) {
finalAnswer[i].Questions.push(val);
} else {
// *issue here*
finalAnswer.push({ pageNumber: val.pageNumber, Questions: [val] });
}
});
} else {
finalAnswer.push({ pageNumber: val.pageNumber, Questions: [val] });
}
console.log("finalAnswer", JSON.stringify(finalAnswer));
});
Im getting issue in the issue here section.
Im getting issue in the issue here section.
2
Answers
There’s no need to call the filter function to find the questions. Also, you’re pushing inside the main array, instead, questions need to get appended in that page nos question key. The above code does the work!
You can try the following code. I think it may help you.