猿问

请各位大佬指点!平级转树结构求老司机指点!

vardata={
"organization":[
{
"id":"1",
"pid":"0",
"organization":"/A"
},
{
"id":"2",
"pid":"0",
"organization":"/AA"
},
{
"id":"11",
"pid":"1",
"organization":"/A/B"
},
{
"id":"22",
"pid":"2",
"organization":"/AA/BB"
},
{
"id":"44",
"pid":"2",
"organization":"/AA/CC"
}
],
"user":[
{
"id":"xxxx",
"pid":"2",
"email":"yu@test.com",
"organization":"/A",
"display_name":"玉"
},
{
"id":"yyy",
"pid":"2",
"email":"yy@test.com",
"organization":"/A/B",
"display_name":"哈"
},
{
"id":"zzzz",
"pid":"22",
"email":"nn@test.com",
"organization":"/AA/BB",
"display_name":"欧式"
},
{
"id":"hhhh",
"pid":"44",
"email":"yfef@test.com",
"organization":"/AA/CC",
"display_name":"红"
},
{
"id":"effef",
"pid":"44",
"email":"yfesf@test.com",
"organization":"/AA/CC",
"display_name":"xe"
}
]
}
如果是organization数组中的话title字段显示组织,如果是user数组中的话title字段显示email
如何把以上结构转成树结构?
偶然的你
浏览 485回答 2
2回答

jeck猫

看你这个其实只有组织是树结构,不过树结构中的一些叶子节点是人员。和一般的平级转树形也差不多,我写一下思路吧:1.声明一个空对象info={},遍历organization数组,给每个org加上children字段,并设置title字段,将组织id和organization映射放到info中,做快速索引。2.再次遍历orgnization,对于每一项org,通过pid从info中找到其父级parent,将org追加到paren.children3.对于user列表,同样遍历,类似步骤2看到楼下写了O(n^2)以上时间复杂度的代码,还是贴一下O(n)的代码吧:functiontoTree(data){let{organization:orgList,user:userList}=dataletresult=[]letorgInfo={}//快速映射orgList.forEach(org=>{orgInfo[org.id]=orgorg.children=[]org.title=org.organization})orgList.forEach(org=>orgInfo[org.pid]?orgInfo[org.pid].children.push(org):result.push(org))userList.forEach(user=>{user.title=user.emailorgInfo[user.pid]&&orgInfo[user.pid].children.push(user)})returnresult}调用:letresult=toTree(data)console.log(JSON.stringify(result))输出:[{"id":"1","pid":"0","organization":"/A","children":[{"id":"11","pid":"1","organization":"/A/B","children":[],"title":"/A/B"}],"title":"/A"},{"id":"2","pid":"0","organization":"/AA","children":[{"id":"22","pid":"2","organization":"/AA/BB","children":[{"id":"zzzz","pid":"22","email":"nn@test.com","organization":"/AA/BB","display_name":"欧式","title":"nn@test.com"}],"title":"/AA/BB"},{"id":"44","pid":"2","organization":"/AA/CC","children":[{"id":"hhhh","pid":"44","email":"yfef@test.com","organization":"/AA/CC","display_name":"红","title":"yfef@test.com"},{"id":"effef","pid":"44","email":"yfesf@test.com","organization":"/AA/CC","display_name":"xe","title":"yfesf@test.com"}],"title":"/AA/CC"},{"id":"xxxx","pid":"2","email":"yu@test.com","organization":"/A","display_name":"玉","title":"yu@test.com"},{"id":"yyy","pid":"2","email":"yy@test.com","organization":"/A/B","display_name":"哈","title":"yy@test.com"}],"title":"/AA"}]如有问题请追问,如有帮助请给个赞~,~
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答