具有层级关系的扁平化数组转化成树形结构数组
// 递归查找父级及其子级节点 nestFn(id) { let a = []; this.resJson.forEach(item => { if (item.fatherid == id) { let { fatherid, roleid, rolelevel, rolename } = item; a.push({ fatherid, roleid, rolelevel, rolename, children: this.nestFn(roleid) }) } }) return a; }, deptFunc() { this.resJson = JSON.parse(treeJson); let deptArr = []; // 转化后的结果数据 this.resJson.forEach((item, index) => { if (Number(item.fatherid) < 0) { // 查找最外层节点数据 let { fatherid, roleid, rolelevel, rolename } = item; deptArr.push({ fatherid, roleid, rolelevel, rolename, children: this.nestFn(roleid) }) } }); },
下图是98条具有层级关系的扁平化数组
下图是转化后的结果数据
转换思路:父级与子级的关系是通过fatherid与roleid关联的,子元素的‘fatherid===父元素的roleid’,由此可以递归出层级关系的数据