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即为树状结构(图)