@@ -103,34 +103,45 @@ let originalObj = [
103
103
104
104
// 1. 递归
105
105
// 处理parentData 和childrenData 之间关系的函数
106
- function parseChildrenToParent ( parentData , childrenData ) {
107
- childrenData . forEach ( item => {
108
- const tempData = parentData . find ( _item => _item . id == item . pid ) ;
109
- if ( ! tempData ) return ;
110
- tempData . children = tempData . children ?? [ ] ;
111
- tempData . children . push ( item ) ;
112
- // if (tempData.children) {
113
- // // 有值 递归
114
- // tempData.children.push(item);
115
- // } else {
116
- // tempData.children = [item];
117
- // }
118
- parseChildrenToParent ( [ item ] , childrenData ) ;
119
- } ) ;
120
- }
106
+ // function parseChildrenToParent(parentData, childrenData) {
107
+ // childrenData.forEach(item => {
108
+ // const tempData = parentData.find(_item => _item.id == item.pid);
109
+ // if (!tempData) return;
110
+ // tempData.children = tempData.children ?? [];
111
+ // tempData.children.push(item);
112
+ // // if (tempData.children) {
113
+ // // // 有值 递归
114
+ // // tempData.children.push(item);
115
+ // // } else {
116
+ // // tempData.children = [item];
117
+ // // }
118
+ // parseChildrenToParent([item], childrenData);
119
+ // });
120
+ // }
121
+
122
+ // function arrayToTree(arr) {
123
+ // let tree = [];
121
124
122
- function arrayToTree ( arr ) {
123
- let tree = [ ] ;
125
+ // function findParent(arr, pid = 0) {
126
+ // const parentData = arr.filter(item => item.pid == 0),
127
+ // childrenData = arr.filter(item => item.pid != 0);
128
+ // parseChildrenToParent(parentData, childrenData);
129
+ // tree = parentData;
130
+ // }
124
131
125
- function findParent ( arr , pid = 0 ) {
126
- const parentData = arr . filter ( item => item . pid == 0 ) ,
127
- childrenData = arr . filter ( item => item . pid != 0 ) ;
128
- parseChildrenToParent ( parentData , childrenData ) ;
129
- tree = parentData ;
130
- }
132
+ // findParent(arr);
133
+ // return tree;
134
+ // }
131
135
132
- findParent ( arr ) ;
133
- return tree ;
134
- }
136
+ // console.log(arrayToTree(originalObj));
137
+
138
+ // 2. 双重遍历
139
+ const formatData = arr => {
140
+ return arr . filter ( item => {
141
+ const _arr = arr . filter ( _item => _item . pid == item . id ) ;
142
+ _arr . length && ( item . children = _arr ) ;
143
+ return item . pid === 0 ;
144
+ } ) ;
145
+ } ;
135
146
136
- console . log ( arrayToTree ( originalObj ) ) ;
147
+ console . log ( formatData ( originalObj ) ) ;
0 commit comments