亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

【比較難】JS多層遞歸遍歷求解答!

【比較難】JS多層遞歸遍歷求解答!

LEATH 2019-10-10 15:58:28
小弟初學js,遇到一個難題,關于把一個多層數據結構的轉換成treeview可識別的格式問題原數據格式為:{"root":"body","structure":{"body":["head","foot"],"head":["control","tabs"],"control":["c123","c456","c789"],"tabs":["33","44"],"foot":["footLeft","divEnd"],"footLeft":["footLeftContainer"],"footLeftContainer":["add22","ffff","fff"],"divEnd":["divEnd$111"]}};期望處理成的格式為:[{text:"body",nodes:[{text:"head",nodes:[{text:"control",nodes:[{text:"c123"},{text:"c456"},{text:"c789"}]},{text:"tabs",nodes:[{text:"t33"},{text:"t44"}]}]},{text:"foot",nodes:[{text:"footLeft",nodes:[{text:"footLeftContainer",nodes:[{text:"add22"},{text:"ffff"},{text:"fff"}]}]},{text:"divEnd",nodes:[{text:"divEnd$111"}]}]}]}]原理就是從structure中層層找child,起始點是root節點的值(即"body")每個節點的child如果不在structure一級節點中,則認為是葉子節點想了一天,沒有好辦法,來求助各位前輩
查看完整描述

2 回答

?
慕尼黑5688855

TA貢獻1848條經驗 獲得超2個贊

constdata={
root:'body',
structure:{
body:['head','foot'],
head:['control','tabs'],
control:['c123','c456','c789'],
tabs:['33','44'],
foot:['footLeft','divEnd'],
footLeft:['footLeftContainer'],
footLeftContainer:['add22','ffff','fff'],
divEnd:['divEnd$111'],
},
};
/**
*@param{typeofdata}data
*/
functionconver(data){
constret=[];
constcoll=data.structure;
constroot={text:data.root};
constmap={[data.root]:root};
Object.keys(coll).forEach(key=>{
map[key]=map[key]||{text:key};
coll[key].forEach(item=>{
map[item]=map[item]||{text:item};
});
});
Object.keys(coll).forEach(key=>{
coll[key].forEach(item=>{
if(map[key]){
map[key].nodes=map[key].nodes||[];
map[key].nodes.push(map[item]);
}
});
});
console.log(root);
}
conver(data);
先遍歷每個節點存在hash表里,然后再遍歷,根據parent關系找到父節點.
像樓上一樣,data.structure這個也可以理解為一張圖,key是一個頂點,數組是它的鄰邊集合.非遞歸也可以的
                            
查看完整回答
反對 回復 2019-10-10
  • 2 回答
  • 0 關注
  • 342 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號