const list = [
{
id:1, val: '学校', parentId: null
},
{
id:2, val: '三年级', parentId: 1
},
{
id:3, val: '四年级', parentId: 1
},
{
id:4, val: '1班', parentId: 2
},
{
id:5, val: '1班', parentId: 3
},
{
id:6, val: '2班', parentId: 2
},
{
id:7, val: '2班', parentId: 3
},
{
id:8, val: '甲学生', parentId: 4
},
{
id:9, val: '乙学生', parentId: 5
},
{
id:10, val: '丙学生', parentId: 6
},
{
id:11, val: '丁学生', parentId: 7
},
]
function toTree(array, parentId) {
const children = []
for(let i=0;i<array.length;i++) {
const node = array[i]
if (node.parentId === parentId) {
children.push({
id: node.id,
val: node.val,
children: toTree(array, node.id)
})
}
}
return children
}
const root = list[0]
list.shift()
const tree = {
id: root.id,
val: root.val,
children: toTree(list, root.id)
}
// function toTree(array, parentId) {
// const children = []
// for(let i = 0;i< array.length; i++ ){
// const node = array[i]
// if (node.parentId === parentId) {
// children.push({
// id: node.id,
// val: node.val,
// children: toTree(array, node.id)
// })
// }
// }
// return children
// }
// const root = list[0]
// list.shift()
// const tree = {
// val: root.val,
// id: root.id,
// children: list.length > 0 ? toTree(list, root.id) : []
// }
// console.log( tree)