描述:用 js 写一个函数将以下的数据转化成树结构
// 原始数据结构
const info = {
h3: {
parent: 'h2',
name: '副总经理(市场)'
},
h1: {
parent: 'h0',
name: '公司机构'
},
h7: {
parent: 'h6',
name: '副总经理(总务)'
},
h4: {
parent: 'h3',
name: '销售经理'
},
h2: {
parent: 'h1',
name: '总经理'
},
h8: {
parent: 'h0',
name: '财务总监'
},
h6: {
parent: 'h4',
name: '仓管总监'
},
h5: {
parent: 'h4',
name: '销售代表'
},
h0: {
parent: '',
name: 'root'
}
}
// 方法1:递归实现
function initObjToTree(obj) {
const findChildrenNode = (pid, objRelationMap, obj) => {
if (!objRelationMap[pid] || objRelationMap[pid].length == 0) return []; // 父节点不存在
let result = [];
const childrenNodesList = objRelationMap[pid];
childrenNodesList && childrenNodesList.forEach((cid) => {
result.push({
pid, //父节点 parentId
key: cid, //当前节点 currentId
...obj[cid], //当前节点的其它属性
children: findChildrenNode(cid, objRelationMap, obj), // 该节点的 children 节点数组
});
});
return result;
};
let objRelationMap = {};
for (let key of Object.keys(obj)) {
const currentNode = obj[key];
const { parent } = currentNode;
const parentName = parent == '' ? 'root' : parent;
if (objRelationMap[parentName]) objRelationMap[parentName].push(key);
else objRelationMap[parentName] = new Array(key);
}
let result = findChildrenNode("root", objRelationMap, obj);
console.log("result", result);
}
// 结果 result
[
{ pid: "root", key: "h0", parent: "", name: "root", children: [
{ pid: "h0", key: "h1", parent: "h0", name: "公司机构", children: [
{ pid: "h1", key: "h2", parent: "h1", name: "总经理", children: [
{ pid: "h2", key: "h3", parent: "h2", name: "副总经理(市场)", children: [
{ pid: "h3", key: "h4", parent: "h3", name: "销售经理", children: [
{ pid: "h4", key: "h6", parent: "h4", name: "仓管总监", children: [
{ pid: "h6", key: "h7", parent: "h6", name: "副总经理(总务)",children: []}
]},
{ pid: "h4", key: "h5", parent: "h4", name: "销售代表", children: []}
]}
]}
]}
]},
{ pid: "h0", key: "h8", parent: "h0", name: "财务总监", children: []}
]}
]
// 方法2:对象地址引用
function initObjToTree(info) {
let result = [];
for (let key in info) {
let parent = info[key].parent;
if (parent && info[parent]) {
if (!info[parent].children) {
info[parent].children = [];
}
info[parent].children.push(info[key]);
} else { // 父节点是root
result.push(info[key]);
}
}
console.log("result", result);
console.log("info", info);
}
// 结果 result
{ parent: "", name: "root", children: [
{ parent: "h0", name: "公司机构", children: [
{parent: "h1", name: "总经理", children: [
{ parent: "h2", name: "副总经理(市场)", children: [
{ parent: "h3", name: "销售经理", children: [
{ parent: "h4", name: "仓管总监", children: [
{ parent: "h6", name: "副总经理(总务)" }
]},
{ parent: "h4", name: "销售代表" }
]}
]}
]}
]},
{ parent: "h0", name: "财务总监" }
]}