递归合并数组并添加层级深度及标识

最近做后台权限的时候,因为后端同事不能直接给到我想要的路由权限数据结构,而且分成了两个接口,一个获取所有路由,一个获取增删改查的权限,所以需要自己做一下合并和处理,代码如下:

//找到父级节点并返回key
			findParentKey(list, pid) {
				let tempKey = 
				let tempArr = []
				let forFn = function(treeData, pid) {
					try {
						treeData.forEach( v => {
							if (v.children && v.children.length > 0 && v.id !== pid) {
								forFn(v.children, pid)
							} else {
								if (v.id === pid) {
									tempKey = v.key
									tempArr.push(tempKey)
								}
							}
						})
					} catch (e) {
						console.log(e)
					}
				}
				forFn(list, pid)
				return tempArr
			},
			//设置标识及层级
			setTreeKey() {
				let _this = this
				_this.treeData.forEach((v, i) => {//给最外层初始化一个key
					v.key = 0- + i
				})
				let tempId = 0
				let getTree = (item, level = 1) => {
					item.forEach((v, i) => {
						v.level = level //添加层级
						v.tempId = tempId //添加标识ID
						tempId++
						if (v.pid !== 0) {//如果不为最外层则根据父级key重新设置
							v.key = _this.findParentKey(_this.treeData, v.pid) + - + i
						}
						if (v.children && v.children.length > 0) {
							getTree(v.children, level + 1)
						}
					})
				}
				getTree(_this.treeData)
			},
			//合并数组
			getTreeList() {
				let _this = this
				getPermissionTreeListApi().then(res => {//获取权限数组
					_this.permissionTreeData = res.data
					getMenuTreeListApi().then(ress => {//获取全部路由
						_this.treeData = ress.data
						let getTree = item => {
							item.forEach(v => {
								if (v.children && v.children.length > 0) {
									getTree(v.children)
								} else {
									v.children = JSON.parse(JSON.stringify(_this.permissionTreeData))//将权限赋给最底层路由
									v.children.forEach(n => {
										n.pid = v.id//添加父级ID
									})
								}
							})
						}
						getTree(_this.treeData)
						_this.setTreeKey()//合并之后调用设置标识及层级方法
					})
				})
			},

最终结构及效果如下:

经验分享 程序员 微信小程序 职场和发展