<script>
const rootList = [
{ id: 1, parent: null, text: '菜单1' },
{ id: 2, parent: 1, text: '菜单1-1' },
{ id: 3, parent: 1, text: '菜单1-2' },
{ id: 4, parent: null, text: '菜单2' },
{ id: 5, parent: 4, text: '菜单2-1' }
]
function listToTree(rootList, id, list) {
for (item of rootList) {
if (item.parent == id) {
list.push(item)
}
}
for (item of list) {
item.children = []
listToTree(rootList, item.id, item.children)
}
return list
}
const res = listToTree(rootList, null, [])
console.log(res);
// [
// {
// id: 1, parent: null, text: '菜单1', children: [
// { id: 2, parent: 1, text: '菜单1-1',children:[] },
// { id: 3, parent: 1, text: '菜单1-2',children:[] },]
// },
// {
// id: 4, parent: null, text: '菜单2', children: [
// { id: 5, parent: 4, text: '菜单2-1',children:[] }
// ]
// }
// ]
</script>
04-03
161
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交