I have a questionnaire in which subsequent questions depend on the user's answer. I need to count the number of possible questionnaire paths, find out the number of paths and add all the questionnaire paths to the array. How can i do this?
In my code, I change the structure of the questions and add an array with answers and follow-up questions:
const newQuestionObj = {};
const getAllPath = (arr) => {
const treeStructure = arr.forEach((item) => {
newQuestionObj[item.id] = {
...item,
children: [
...Object.keys(item)
.filter((k) => k.includes("answer"))
.map((k) => ({ ...item[k]
})),
],
};
});
console.log(newQuestionObj);
};
getAllPath(questions);
<script>
const questions = [{
id: "1",
question: "q1",
answer_1: {
text: "a1",
next_question: "2",
},
answer_2: {
text: "a2",
next_question: "3",
},
},
{
id: "2",
question: "q2",
answer_1: {
text: "a1",
next_question: "",
},
answer_2: {
text: "a2",
next_question: "",
},
},
{
id: "3",
question: "q3",
answer_1: {
text: "a1",
next_question: "",
},
answer_2: {
text: "a2",
next_question: "4",
},
},
{
id: "4",
question: "q4",
answer_1: {
text: "a1",
next_question: "",
},
answer_2: {
text: "a2",
next_question: "",
},
},
];
</script>
I need to get an object like this:
{
paths: {
number: 3,
list: [
[{
"q1": "a1"
},
{
"q2": "a1/a2"
}
],
[{
"q1": "a2"
},
{
"q3": "a1"
}
],
[{
"q1": "a2"
},
{
"q3": "a2"
},
{
"q4": "a1/a2"
}
],
]
}
}