把扁平化的数组数据, 转换成树形结构的数组数据
(无论多少层, 都能解决) --- 递归
function arrayToTree(arr, rootNode) {
const tree = []
arr.forEach(item => {
if (item.pid === rootNode) {
// 找到根节点之后, 就去找下面有没有对应的子节点
const children = arrayToTree(arr, item.id)
// 如果 children 的长度大于0, 说明找到了子节点
children.length > 0 ? (item.children = children) : 0
tree.push(item) // 将内容加入数组中
}
})
return tree
}