小弟初学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 回答
SMILET
TA贡献1796条经验 获得超4个赞
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是一个顶点,数组是它的邻边集合.非递归也可以的
添加回答
举报
0/150
提交
取消