SOURCE

function getTreeList(rootList, id, newArr) {
            for (const item of rootList) {
                if (item.parent === id) {
                    newArr.push(item)
                }
            }
 
            //给数组里面再添加一个children的空数组
            for (const i of newArr) {
                i.children = [];
                getTreeList(rootList, i.id, i.children);
 
                if (i.children.length == 0) {
                    delete i.children
                }
            }
            return newArr
        }
 const rootList = [
        { id: 1, parent: null, text: '菜单1' },
        { id: 11, parent: 1, text: '菜单1-1' },
        { id: 12, parent: 1, text: '菜单1-2' },
        { id: 2, parent: null, text: '菜单2' },
        { id: 21, parent: 2, text: '菜单2-1' },
        { id: 22, parent: 2, text: '菜单2-2' },]
        //将数据传入,此时id为null,并且传入一个空数组
        const res = getTreeList(rootList, null, []); 
        console.log(res,777)
console 命令行工具 X clear

                    
>
console