將有父子關系的數組對象轉換成樹形結構數據


原數據:

 1 data: [{
 2     id: 1,
 3     name: '1',
 4 },
 5 {
 6     id: 2,
 7     name: '1-1',
 8     parentId: 1
 9 },
10 {
11     id: 3,
12     name: '1-1-1',
13     parentId: 2
14 },
15 {
16     id: 4,
17     name: '1-2',
18     parentId: 1
19 },
20 {
21     id: 5,
22     name: '1-2-2',
23     parentId: 4
24 },
25 {
26     id: 6,
27     name: '1-1-1-1',
28     parentId: 3
29 },
30 {
31     id: 7,
32     name: '2',
33     parentId: ''
34 },
35 {
36     id: 8,
37     name: '3'
38 },
39 {
40     id: 9,
41     name: '3-1',
42     parentId: 7
43 }
44 ]

轉換方法:

 1 /**
 2  * 該方法用於將有父子關系的數組轉換成樹形結構的數組
 3  * 接收一個具有父子關系的數組作為參數
 4  * 返回一個樹形結構的數組
 5  */
 6 translateDataToTree(data) {
 7     // 沒有父節點的數據
 8     let parents = data.filter(value => value.parentId == 'undefined' || value.parentId == null ||
 9         value.parentId ==
10         '')
11     // 有父節點的數據
12     let children = data.filter(value => value.parentId !== 'undefined' && value.parentId !=
13         null || value.parentId !=
14         '')
15     // 定義轉換方法的具體實現
16     let translator = (parents, children) => {
17         // 遍歷父節點數據
18         parents.forEach((parent) => {
19             // 遍歷子節點數據
20             children.forEach((current, index) => {
21                 // 此時找到父節點對應的一個子節點
22                 if (current.parentId === parent.id) {
23                     // 對子節點數據進行深復制,這里只支持部分類型的數據深復制,對深復制不了解的童靴可以先去了解下深復制
24                     let temp = JSON.parse(JSON.stringify(children))
25                     // 讓當前子節點從temp中移除,temp作為新的子節點數據,這里是為了讓遞歸時,子節點的遍歷次數更少,如果父子關系的層級越多,越有利
26                     temp.splice(index, 1)
27                     // 讓當前子節點作為唯一的父節點,去遞歸查找其對應的子節點
28                     translator([current], temp)
29                     // 把找到子節點放入父節點的children屬性中
30                     typeof parent.children !== 'undefined' ? parent.children
31                         .push(
32                             current) :
33                         parent.children = [current]
34                 }
35             })
36         })
37     }
38     // 調用轉換方法
39     translator(parents, children)
40     // 返回最終的結果    
41     return parents;
42 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM