tree树形结构互转

const treeData = [
    {
        id: 1,
        title: "课程1",
        children: [
            { id: 4, title: "课程1-1" },
            {
                id: 5,
                title: "课程1-2",
                children: [
                    { id: 6, title: "课程1-2-1", children: [{ id: 8, title: "课程1-2-1" },] },
                    { id: 7, title: "课程1-2-2" },
                ],
            },
        ],
    },
    { id: 2, title: "课程2" },
    { id: 3, title: "课程3" },
];
const flatData = [
    { id: 1, parent: 0, title: "课程1" },
    { id: 4, parent: 1, title: "课程1-1" },
    { id: 5, parent: 1, title: "课程1-2" },
    { id: 6, parent: 5, title: "课程1-2-1" },
    { id: 7, parent: 5, title: "课程1-2-2" },
    { id: 2, parent: 0, title: "课程2" },
    { id: 3, parent: 0, title: "课程3" },
]
 
function treeToflat(treeData, res = [], pid = 0) {
    for (let i = 0; i < treeData.length; i++) {
        res.push({
            id: treeData[i].id,
            title: treeData[i].title,
            parent: pid
        })
        if (treeData[i].children) {
            treeToflat(treeData[i].children, res, treeData[i].parent)
        }
    }
    return res;
}
 
 
function flatTotree(list) {
    // let tree = list[0];
    let r = []
    function getChildren(subList, res, parent) {
        for (let i = 0; i < subList.length; i++) {
            console.log(subList[i].id, parent)
            if (subList[i].parent === parent) {
                const newItem = { ...subList[i], children: [] };
                res.push(newItem);
                console.log(res)
                getChildren(subList, newItem.children, subList[i].id)
            }
        }
    }
    getChildren(list, r, 0)
    return r;
}
 
 // 非递归实现
 function formatTree(list) {
    let obj = {}, trees = [];
    list.forEach(item => {
        obj[item.id] = item;
    })
    list.forEach(item => {
        let parent = obj[item.parent];
        if (parent) (parent.children || (parent.children = [])).push(item);
        else trees.push(item) 
    })
    return trees;
}
console.log(JSON.stringify(flatTotree(flatData)));




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值