问题 js 树状结构

问题:

  • 不明白数组怎么就有children字段了,怎么添加的
  • 运行顺序是怎么样的
 1 <script>
 2 
 3 export default {
 4   name: 'app',
 5   data() {
 6     return {
 7       treeData: [
 8         {
 9           id: '1',
10           name: '1',
11           fatherId: '0'
12         },
13         {
14           id: '2',
15           name: '1-1',
16           fatherId: '1'
17         },
18         {
19           id: '3',
20           name: '1-2',
21           fatherId: '1'
22         },
23         {
24           id: '4',
25           name: '1-1-1',
26           fatherId: '2'
27         },
28         {
29           id: '5',
30           name: '1-1-2',
31           fatherId: '2'
32         },
33         {
34           id: '6',
35           name: '2',
36           fatherId: '0'
37         },
38         {
39           id: '7',
40           name: '1-2-1',
41           fatherId: '3'
42         }
43       ]
44     }
45   },
46 
47   methods: {
48     getTreeData: function() {
49       const map = {}
50       const val = []
51       this.treeData.forEach((item) => {
52         map[item.id] = item
53       })
54       this.treeData.forEach((item) => {
55         const parent = map[item.fatherId]
56         console.log(item)
57         console.log(parent)
58         if (parent) {
59           (parent.children || (parent.children = [])).push(item)
60         } else {
61           val.push(item)
62         }
63       })
64     }
65   },
66   created() {
67     this.getTreeData()
68   }
69 }
原文地址:https://www.cnblogs.com/svvv/p/13913069.html