node.js 递归组织树状结构方法

js递归组织树状结构函数方法

function recursionDataTree(dataList,pid){
    let resultList = [];
    if (!dataList) return null; 
    for (const map of dataList) {
        let bmid_new = map["id"];
        let parentId = map["pid"];
        if (pid==parentId) {
            const data = map;
           let childrenList = this.recursionDataTree(dataList, bmid_new);
            if (childrenList)
            data["children"]= childrenList;
            resultList.push(data);
        }
    }
    return resultList;
  }

eg:

    let dltest=[{id:'1',pid:'0',name:'大类1'},{id:'2',pid:'0',name:'大类2'},{id:'3',pid:'0',name:'大类3'},{id:'4',pid:'1',name:"中类11"},{id:'5',pid:'1',name:"中类12"},{id:'6',pid:'4',name:"小类111"}];
    let resultdata=recursionDataTree(dltest,'0');

结构如下:

[{"id":"1","pid":"0","name":"大类1","children":[{"id":"4","pid":"1","name":"中类11","children":[{"id":"6","pid":"4","name":"小类111","children":[]}]},{"id":"5","pid":"1","name":"中类12","children":[]}]},{"id":"2","pid":"0","name":"大类2","children":[]},{"id":"3","pid":"0","name":"大类3","children":[]}]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值