递归,将普通数组转换成树形结构
递归,将普通数组转换成树形结构
很多时候我们需要的数据都是树形结构数据,但很多时候并不是所有数据都是我们想要的,所以需要我们自己处理封装函数
// 将数组转换为树结构 parseArrayToTree(array) { let tree = []; let root = this.getRootObj(array); debugger; if (root) { tree.push(root); this.setChild(root, array); } console.log(tree); return tree; }, // 获取树的根节点 getRootObj(array) { let root = null; if (array) { array.forEach(function (item, index, arr) { if (item.parentId == -1) { // 根节点的id为-1 这个要与后台确认 root = item; } }) } return root; }, // 递归设置树结构子节点 setChild(root, array) { let temp = this; array.forEach(function (item, index, arr) { if (item.parentId === root.specId) { if (root.child) { root.child.push(item); } else { root.child = []; root.child.push(item); } temp.setChild(item, array) } }) },
调用方法
let treeValue = parseArrayToTree(tree)