Bonjour,
J'aimerais implémenter un algorithme pour créer un arbre avec une condition qui s'auto remplie d'un name et de children à chaque boucle si la condition est à true.
Mon entrée :
et ma sortie attendue :Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53 [{ id: 1, entitled: "first question", questions: [ { id: 1, entitled: "Do you have a car ?", answers: [ { id: 1, entitled: "Yes", conditionalSection: 2 }, { id: 2, entitled: "No", conditionalSection: 3 }, ], }, ], }, { id: 2, entitled: "section yes", questions: [ { id: 1, entitled: "Do you have an electric car ?", answers: [ { id: 1, entitled: "Yes", conditionalSection: 4 }, { id: 2, entitled: "No", conditionalSection: 4 }, ], }, ], }, { id: 3, entitled: "section no", questions: [ { id: 1, entitled: "Do you have a bicycle ?", answers: [ { id: 1, entitled: "Yes", conditionalSection: 4 }, { id: 2, entitled: "No", conditionalSection: 4 }, ], } ], }, { id: 4, entitled: "end", questions: [ { id: 1, entitled: "Do you have any comments ?", } ], }, ];
j'ai essayé de faire quelque chose comme ça:Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 { name: "Do you have a car ?", children: [ { name: "Yes", children: [ { name: "Do you have an electric car ?", children: [ { name: "Yes", children: [{ name: "Do you have any comments ?" }] }, { name: "No", children: [{ name: "Do you have any comments ?" }] }, ], }, ], }, { name: "No", children: [ { name: "Do you have a bicycle ?", children: [ { name: "Yes", children: [{ name: "Do you have any comments ?" }] }, { name: "No", children: [{ name: "Do you have any comments ?" }] }, ], }, ], }, ], };
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 const output = [] const prototype = { name: "", children: [] }; sections.forEach((section, index) => { prototype[index] = prototype; }); sections.forEach((section, index) => { let next = prototype; section.questions.forEach((question, index) => { let now = next; next = prototype; question.answers((answer, index) => { if (answer.conditionalSection!==null){ output.push(next) } }); }); });