哈希表实现id,pid转树形结构

 1  var source = [{
 2       id: 1, pid: 0, name: 'body'}, {
 3       id: 2, pid: 1, name: 'title'}, {
 4       id: 3, pid: 1, name: 'div'}, {
 5       id: 4, pid: 3, name: 'span'}, {
 6       id: 5, pid: 3, name: 'icon'}, {
 7       id: 6, pid: 4, name: 'subspan'}]
 8     function toTree(data) {
 9       let result = []
10       if (!Array.isArray(data)) {
11         return result
12       }
13       data.forEach(item => {
14           delete item.children;
15       });
16       let map = {};
17       data.forEach(item => {
18           map[item.id] = item;
19       });
20       data.forEach(item => {
21         let parent = map[item.pid];
22         if (parent) {
23             (parent.children || (parent.children = [])).push(item);
24         } else {
25             result.push(item);
26         }
27       });
28       return result;
29     }
30     console.log(toTree(source))

 

posted on 2019-03-05 11:51  时光游弋  阅读(724)  评论(0编辑  收藏  举报