js递归构造树方法

js递归构造树方法
/**
  * 递归构造树
  *
  * @param oldArr 旧数组
  * @param pid 根节点id
  * @return newArr 树结构数组
  */
function buildTreeData(oldArr, pid) {
    var newArr = [];
    var self = this;
    oldArr.map(function (item) {
    	// item.parentId为上级节点key
        if (item.parentId == pid) {
        	// 树结构json结构
            var obj = {
                id: item.id,	//原数组的节点id
                parentId: item.parentId,	//原数组的上级节点id
                name: item.name		//原数组的名称
            }
            var child = this.buildTreeData(oldArr, item.id);
            if (child.length > 0) {
                obj.child = child	// obj.child为树结构子节点key
            }
            newArr.push(obj)
        }
    })
    return newArr;
}

使用:

// 后台返回的json结果
var arr = {"msg":"操作成功","code":0,"nodes":[{"id":"1000","parentId":"0","name":"山东总公司"},{"id":"1003","parentId":"0","name":"山西总公司22"},{"id":"1001","parentId":"1000","name":"济南公司"},{"id":"1005","parentId":"1003","name":"大同公司"},{"id":"1002","parentId":"1000","name":"青岛公司"},{"id":"1004","parentId":"1003","name":"太原公司"},{"id":"1006","parentId":"1000","name":"德州公司"},{"id":"1021","parentId":"1000","name":"潍坊公司"},{"id":"1007","parentId":"1001","name":"市中区分管部"},{"id":"1015","parentId":"1002","name":"市南区"},{"id":"1020","parentId":"1005","name":"平城区"},{"id":"1008","parentId":"1001","name":"高新区分管部"},{"id":"1016","parentId":"1002","name":"市北区"},{"id":"1009","parentId":"1001","name":"历城区分管部"},{"id":"1010","parentId":"1001","name":"历下区分管部"},{"id":"1011","parentId":"1001","name":"长清区分管部"},{"id":"1022","parentId":"1001","name":"章丘区分管部"},{"id":"1012","parentId":"1007","name":"开发部"},{"id":"1017","parentId":"1008","name":"开发部"},{"id":"1013","parentId":"1007","name":"采购部"},{"id":"1018","parentId":"1008","name":"采购部"},{"id":"1014","parentId":"1007","name":"销售部"},{"id":"1019","parentId":"1008","name":"销售部"},{"id":"1023","parentId":"1007","name":"技术部"},{"id":"0","name":"部门管理"}]}
// 调用
var treeArr = buildTreeData(arr.nodes,'0');
// treeArr即为树状结构(图)

树结构层次

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值