12.扁平数组<->树形结构

12.扁平数组->树形结构:

参考视频

        let arr = [
            { id: 1, name: '部门1', parent_id: 0 },
            { id: 2, name: '部门2', parent_id: 1 },
            { id: 3, name: '部门3', parent_id: 1 },
            { id: 4, name: '部门4', parent_id: 3 },
            { id: 5, name: '部门5', parent_id: 4 },
        ]
        function convert(arr) {
            const result = [];
            // 转为键值对形式 {1: { id: 1, name: '部门1', parent_id: 0 }}
            // pre:累加 , cur:当前数组中的元素 , {}:初始值为对象
            const map = arr.reduce((pre, cur) => {
                pre[cur.id] = cur;
                return pre;
            }, {});
            // 遍历数组中的每一个对象,如 {id:1} 、 {id:2}
            for (const item of arr) {
                if (item.parent_id === 0) {
                    // 当p_id=0时,将其直接插入到数组中
                    result.push(item);
                    continue;
                }
                // 如果p_id在map中
                if (item.parent_id in map) {
                    // 新建parent,比如表示id:1是父节点
                    const parent = map[item.parent_id];
                    // parent.children 初始时为空[]
                    parent.children = parent.children || [];
                    // 将array中的每一项插入到对应的子元素中
                    parent.children.push(item);
                }
            }
            return result;
        }
        const res = convert(arr);
        console.log(res);

树形结构->扁平数组

        let arr = [
            {
                id: 1,
                title: '节点1',
                parent_id: 0,
                children: [
                    {
                        id: 2,
                        title: '节点1_1',
                        parent_id: 1
                    }
                ]
            }
        ]
        function convertToArr(arr) {
            return arr.reduce((pre, cur) => {
                const { id, title, parent_id, children = [] } = cur;
                return pre.concat([{ id, title, parent_id, }], convertToArr(children));
            }, []);
        }
        const res = convertToArr(arr);
        console.log(res);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值