例子:
const list = [
{ id: 0, name: "yx" },
{ id: 2, name: "yj", superId: 0 },
{ id: 4, name: "yd", superId: 0 },
{ id: 7, name: "yf", superId: 2 }
]
//转换为
const tree = {
id: 0,
name: "yx",
children: [
{
id: 2,
name: "yj",
children: [
{ id: 7, name: "yf" }
]
},
{ id: 4, name: "yd" }
]
}
这种情况在前端渲染tree组件时时常会遇到,
本人比较笨,思路就是遍历递归,比如这里没有superId就是root
root中创建为“children”的key,value就是遍历数组找到superId等于root的id的对象,然后递归root的children中的对象
每当将list中的一项添加到tree中对应的级别里时,从list中删除该项,
当list的length为0时就是递归的出口
这里用了lodash提供的工具函数,当然也可以splice(注意遍历时的下标)。
// ****** 对象数组 ==> 树
__arrToTree(arr, pid = "superiorId", id = "id") {
let tree = [];
_.remove(arr, item => {
if (item[pid] === "0"){
tree.push(item)
return true
}
return false
})
// 递归
const getChildren = (arr, tree, pid, id) => {
if (!arr || !tree)return;
tree.forEach(i => {
_.remove(arr, j => {
if (j[pid] === i[id]) {
i.children.push(j)
return true
}
return false
})
if (i.children.length === 0) {
delete i.children;
}else {
getChildren(arr, i.children, pid, id)
}
})
}
getChildren(arr, tree, pid, id)
return tree
}
// ******
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。