質問編集履歴
1
解決案追記
title
CHANGED
File without changes
|
body
CHANGED
@@ -75,4 +75,52 @@
|
|
75
75
|
}
|
76
76
|
]
|
77
77
|
```
|
78
|
-
`map` と`filter`を多数ネストしできなくもないですが、行列が変更になっても対応できるアルゴリズムが知りたいです。
|
78
|
+
`map` と`filter`を多数ネストしできなくもないですが、行列が変更になっても対応できるアルゴリズムが知りたいです。
|
79
|
+
|
80
|
+
# 解決案
|
81
|
+
```javascript
|
82
|
+
const tableToTreeObjArr = (tableData, childListKey) => {
|
83
|
+
|
84
|
+
// ヘッダー取得
|
85
|
+
const header = tableData[0]
|
86
|
+
|
87
|
+
// 行単位の処理
|
88
|
+
const addRowToTree = (treeArray, row, header) => {
|
89
|
+
|
90
|
+
let list = treeArray
|
91
|
+
|
92
|
+
for (let i = 0; i < row.length; ++ i) {
|
93
|
+
|
94
|
+
// 最終列以外 子配列を格納する親オブジェクトを生成
|
95
|
+
if (i < row.length - 1) {
|
96
|
+
|
97
|
+
// ヘッダーから列名取得
|
98
|
+
const key = header[i]
|
99
|
+
|
100
|
+
// 親オブジェクトがまだ存在しない場合は生成
|
101
|
+
let obj = list.find(col => {
|
102
|
+
return col[key] === row[i]
|
103
|
+
})
|
104
|
+
if (!obj) {
|
105
|
+
obj = { [key]: row[i], [childListKey]: [] }
|
106
|
+
list.push(obj)
|
107
|
+
}
|
108
|
+
|
109
|
+
// list変数の参照先を子配列に変更
|
110
|
+
list = obj[childListKey]
|
111
|
+
|
112
|
+
// 最終列 子配列への格納のみ行う
|
113
|
+
} else {
|
114
|
+
list.push(row[i])
|
115
|
+
}
|
116
|
+
}
|
117
|
+
|
118
|
+
return treeArray
|
119
|
+
}
|
120
|
+
|
121
|
+
// ヘッダー以降の行を配列に畳み込み
|
122
|
+
return tableData.slice(1).reduce((treeArray, row) => {
|
123
|
+
return addRowToTree(treeArray, row, header)
|
124
|
+
}, [])
|
125
|
+
}
|
126
|
+
```
|