回答編集履歴

3

追記

2020/09/13 11:55

投稿

Zuishin
Zuishin

スコア28669

test CHANGED
File without changes

2

追記

2020/09/13 11:55

投稿

Zuishin
Zuishin

スコア28669

test CHANGED
@@ -71,3 +71,33 @@
71
71
  console.log(JSON.stringify(tree, undefined, 2));
72
72
 
73
73
  ```
74
+
75
+
76
+
77
+ ### 追記 id が連番でない、またはルートが複数ある場合
78
+
79
+
80
+
81
+ ```JavaScript
82
+
83
+ const result = datas
84
+
85
+ .map(a => { return {"id":a.id, "children":[]}; })
86
+
87
+ .reduce((result, item) => { result[item.id] = item; return result; }, {});
88
+
89
+ for (const datum of datas.filter(a => a.parent !== null)) {
90
+
91
+ result[datum.parent].children.push(result[datum.id]);
92
+
93
+ }
94
+
95
+ const tree = datas
96
+
97
+ .filter(a => a.parent === null)
98
+
99
+ .map(a => result[a.id]);
100
+
101
+ console.log(JSON.stringify(tree, undefined, 2));
102
+
103
+ ```

1

修正

2020/09/13 11:55

投稿

Zuishin
Zuishin

スコア28669

test CHANGED
@@ -60,12 +60,14 @@
60
60
 
61
61
  const result = datas.map(a => { return {"id":a.id, "children":[]}; });
62
62
 
63
- for (let datum of datas.filter(a => a.parent !== null)) {
63
+ for (const datum of datas.filter(a => a.parent !== null)) {
64
64
 
65
65
  result[datum.parent].children.push(result[datum.id]);
66
66
 
67
67
  }
68
68
 
69
+ const tree = [result[0]];
70
+
69
- console.log(JSON.stringify([result[0]]));
71
+ console.log(JSON.stringify(tree, undefined, 2));
70
72
 
71
73
  ```