treeData(data){
let cloneData = JSON.parse(JSON.stringify(data)) //对源数据深拷贝
return cloneData.filter(father => {
let branchArr = cloneData.filter(children => father.id === children.fatherId //返回每一项的子级数据
if (branchArr.length > 0) {
father.children = branchArr //如果存在子级,则给父级增加一个children属性并赋值
}
return father.fatherId === null //返回第一层
})
}
export function populateChildren (nodes) {
if (!nodes) return {}
Object.values(nodes).forEach(v => {
if (!v.children) v.children = [] //不存在子级将其置空
if (v.parentId && nodes[v.parentId]) {
const parentNode = nodes[v.parentId]
if (!parentNode.children) parentNode.children = []
parentNode.children.push(v.id)
}
})
const topParents = Object.values(nodes).filter(n => !n.parentId) //找到每棵树的树顶
topParents.forEach(t => populateLevel(t, nodes)) //调用populateLevel方法对树的等级进行测量
return nodes
}
function populateLevel (node, nodes) {
if (!node.parentId) {
node.level = 0
}
if (node.children && node.children.length) {
node.children.forEach(nodeId => {
const n = nodes[nodeId]
n.level = node.level + 1
populateLevel(n, nodes)
})
}
}