@@ -135,30 +135,52 @@ const renderHTML = (mat: any) => {
135135} ;
136136
137137// chatGPT
138+ type NestedData = {
139+ [ key : string ] : NestedData | number [ ] ;
140+ } ;
141+
142+ // 各ノードの「総行数」を計算する関数
143+ function countRows ( obj : NestedData | number [ ] ) : number {
144+ if ( Array . isArray ( obj ) ) {
145+ return 1 ;
146+ }
147+ let count = 0 ;
148+ for ( const key in obj ) {
149+ count += countRows ( obj [ key ] ) ;
150+ }
151+ return count ;
152+ }
153+
138154function createRecursiveTable ( data : NestedData ) : string {
139155 let html = "<table border='1'>" ;
140156 html += "<thead><tr><th>Key</th><th>Value</th></tr></thead><tbody>" ;
141157
142- function traverse ( obj : NestedData | number [ ] , depth = 0 ) : string {
158+ function traverse ( obj : NestedData | number [ ] , includeTr : boolean = true ) : string {
143159 let rows = "" ;
144160
145161 if ( Array . isArray ( obj ) ) {
146- // 配列の場合、単純に値を出力
162+ // 配列ならそのままValue出力
163+ if ( includeTr ) rows += `<tr>` ;
147164 rows += `<td>${ obj . join ( ", " ) } </td></tr>` ;
148165 } else {
149166 for ( const key in obj ) {
150167 const value = obj [ key ] ;
151168 const rowspan = countRows ( value ) ;
152169
153- rows += `<tr>` ;
170+ if ( includeTr ) rows += `<tr>` ;
154171 rows += `<td rowspan="${ rowspan } ">${ key } </td>` ;
155172
156- if ( Array . isArray ( value ) ) {
157- // 次が配列なら、すぐ値を出す
158- rows += `<td>${ value . join ( ", " ) } </td></tr>` ;
159- } else {
160- // 次がオブジェクトなら、さらに潜る
161- rows += traverse ( value , depth + 1 ) ;
173+ // 最初の子要素は同じ<tr>の中に入れる
174+ rows += traverse ( value , false ) ;
175+
176+ // 2個目以降の子要素は<tr>を新たに作る
177+ if ( ! Array . isArray ( value ) ) {
178+ const keys = Object . keys ( value ) ;
179+ for ( let i = 1 ; i < keys . length ; i ++ ) {
180+ const childKey = keys [ i ] ;
181+ rows += `<tr><td rowspan="${ countRows ( value [ childKey ] ) } ">${ childKey } </td>` ;
182+ rows += traverse ( value [ childKey ] , false ) ;
183+ }
162184 }
163185 }
164186 }
0 commit comments