ele UI 的树级菜单的数据要求是这种嵌套的,但是Ztree的老用发的是
var zNodes =[ { id:1, pId:0, name:"zTree Home", pid:0}, { id:2, pId:0, name:"zTree in Google",pid:0},
{ id:3, pId:0, name:"zTree in Iteye",pid:1}]
这种以pid来识别父级关系的,话不多说转换
//将数组转成嵌套的 buildTree (arr) { let temp = {} let tree = {} // 数组转 键值对 arr.forEach(item => { temp[item.id] = item }) let tempKeys = Object.keys(temp) tempKeys.forEach(key => { // 获取当前项 let item = temp[key] // 当前项 pId let _itemPId = item.pid // 获取父级项 let parentItemByPid = temp[_itemPId] if (parentItemByPid) { if (!parentItemByPid.children) { parentItemByPid.children = [] } parentItemByPid.children.push(item) } else { tree[item.id] = item } }) // 对象转数组并返回 return Object.keys(tree).map(key => tree[key]) },
!!!