js遍历树,多层嵌套for循环,递归
- 一、目的
- 源数据示例
- 二、如何获得数据
- 多层for循环嵌套遍历树数据
- 递归遍历树数据
一、目的
遍历获取树数据中的部分数据。
源数据示例
menuType=2的数据为按钮,按钮可以在一级菜单下也可以在二级菜单下,层级不固定。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45// 示例数据 menuType=0为一级菜单,1为按钮,2为二级菜单 let menuTreeList = [ { "id": "cfda8029dfb311e7b555201a068c6482", "name": "系统管理", "menuType": 0, "children": [ { "id": "3873ccc2dfda11e7b555201a068c6483", "name": "菜单管理", "menuType": 2, "children": [ { "id": "18bf8d5df09511e78a57201a068c6484", "name": "新增", "menuType": 1 }, { "id": "18bf8d5df09511e78a57201a068c6485", "name": "修改", "menuType": 1 } ] } ] }, { "id": "cfda8029dfb311e7b555201a068c6486", "name": "设备管理", "menuType": 0, "children": [ { "id": "18bf8d5df09511e78a57201a068c6487", "name": "新增", "menuType": 1 }, { "id": "18bf8d5df09511e78a57201a068c6488", "name": "修改", "menuType": 1 } ] } ]
二、如何获得数据
因为源数据是树形,要用到的也只有menuType=1的数据,所以如果每次判断时都遍历整个树时都会遍历到很多不必要的数据,如menuType=0或者2的数据是不需要的,所以拿到数据的时候就把需要的数据取出来转换成普通数组,这样判断的时候遍历起来更快速与方便。
多层for循环嵌套遍历树数据
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28for (let item of menuTreeList) { if (item.menuType === 1) { menuList.push({ name: item.name, url: item.url, id: item.id }); } for (let towMenus of item.children) { if (towMenus.menuType === 1) { menuList.push({ name: towMenus.name, url: towMenus.url, id: towMenus.id }); } for (let threeMenus of towMenus.children) { if (threeMenus.menuType === 1) { menuList.push({ name: threeMenus.name, url: threeMenus.url, id: threeMenus.id }); } } } }
上面的源代码只有三级,就已经很长了,而且每多一级就要多想一个变量名,如果层级更多,那光想变量名就头疼了,从可读性与维护性来说都不适合,所以要用递归来实现。
递归遍历树数据
递归,就是在运行的过程中调用自己。用代码来说就是下面第二段代码。
调用方法:
复制代码
1
2
3
4
5
6
7// 菜单按钮权限数据 let menuBtnList = []; // 调用递归方法获得按钮数据 this.getMenuBtnList(resData, menuBtnList); // 保存菜单按钮权限数据至vuex中 this.$store.commit('updateMenuBtnList', {menuBtnList: menuBtnList});
递归方法实现:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14getMenuBtnList (menuTreeList, menuList) { for (let item of menuTreeList) { if (item.menuType === 1) { menuList.push({ name: item.name, url: item.url, id: item.id }); } else if (item.children.length > 0 ) { this.getMenuBtnList(item.children, menuList); } } }
最后
以上就是伶俐汉堡最近收集整理的关于js遍历树,多层嵌套for循环,递归一、目的二、如何获得数据的全部内容,更多相关js遍历树,多层嵌套for循环,递归一、目内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复