JavaScript数组和树互相转换

一、需求

在前端业务场景中,将数组转为树型数据结构说经常会遇到的需求。
将如下数组:

let arr = [
    { id: 1, name: '部门1', pid: 0 },
    { id: 2, name: '部门2', pid: 1 },
    { id: 3, name: '部门3', pid: 1 },
    { id: 4, name: '部门4', pid: 3 },
    { id: 5, name: '部门5', pid: 4 },
]

转为对应树(对象)结构:

[
    {
        "id": 1,
        "name": "部门1",
        "pid": 0,
        "children": [
            {
                "id": 2,
                "name": "部门2",
                "pid": 1,
                "children": []
            },
            {
                "id": 3,
                "name": "部门3",
                "pid": 1,
                "children": [
                    // 结果 ,,,
                ]
            }
        ]
    }
]

二、数组转树

递归实现

function getChildren(arr, res, pid){
    for(let i of arr){
        if(i.pid === pid){
            let newItem = {
                ...i,
                children: []
            };
            res.push(newItem);
            getChildren(arr.filter(item => item.id !== i.id), newItem.children, i.id);
        }
    }
}

function arrayToTree(arr, pid) {
    let res = [];
    getChildren(arr, res, pid);
    return res;
}

非递归实现

先把数据转成Map去存储,之后遍历的同时借助对象的引用,直接从Map找对应的数据做存储。

相比于递归,非递归具有更高的性能。

function arrayToTree(items) {
    let res = [];
    let hash = [];
    for(let i of items){
        const {id, pid} = i;

        if(!hash[id]){
            hash[id] = {
                children: []
            }
        }

        hash[id] = {
            ...i,
            children: hash[id]['children']
        }

        const item = hash[id];

        if(pid === 0){
            res.push(item)
        }else{
            if(!hash[pid]){
                hash[pid] = {
                    children: []
                }
            }
            hash[pid].children.push(item);
        }
    }
    return res;
}

结果:
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小绵杨Yancy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值