当前位置: 代码迷 >> JavaScript >> 将一个JSON格式的数据转换成另一个树型构造的JSON数据,请高手指教!SOS班主
  详细解决方案

将一个JSON格式的数据转换成另一个树型构造的JSON数据,请高手指教!SOS班主

热度:333   发布时间:2013-07-04 11:45:51.0
将一个JSON格式的数据转换成另一个树型结构的JSON数据,请高手指教!SOS班主
本帖最后由 asimplefire 于 2013-06-05 19:36:07 编辑
如下一个JSON数据,当ID等于ParentID时,为树的根节点(是唯一的),如"y001p"属性为根节点。
ParentID与另一属性的ID相关联,层次可能也是无限级的。

{
   "t001p":{"ID":"t001","Name":"node_t001","ParentID":"y001"},
   "s001p":{"ID":"s001","Name":"node_t001","ParentID":"y001"},
   "m001p":{"ID":"m001","Name":"node_m001","ParentID":"y001"},
   "r001p":{"ID":"r001","Name":"node_r001","ParentID":"s001"},
   "u001p":{"ID":"u001","Name":"node_u001","ParentID":"s001"},
   "h001p":{"ID":"h001","Name":"node_h001","ParentID":"s001"},
   "e001p":{"ID":"e001","Name":"node_e001","ParentID":"h001"},
   "k001p":{"ID":"k001","Name":"node_k001","ParentID":"h001"},
   "j001p":{"ID":"j001","Name":"node_j001","ParentID":"m001"},
   "y001p":{"ID":"y001","Name":"node_y001","ParentID":"y001"}
}

需要将以上数据格式转换成如下树型数据格式:

{
   "Name":"node_y001","ID":"y001","children":[
  {"Name":"node_t001",ID:"t001","children":[]},
  {"Name":"node_s001",ID:"s001","children":[
      {"Name":"node_r001","ID":"r001","children":[]},
      {"Name":"node_u001","ID":"u001","children":[]},
      {"Name":"node_h001","ID":"h001","children":[
{"Name":"node_e001","ID":"e001","children":[]},
{"Name":"node_k001","ID":"k001","children":[]}
       ]},
           ]},
  {"Name":"node_m001",ID:"m001","children":[
      {"Name":"node_j001","ID":"j001","children":[]}
  ]}
]
}

请教一下,这个递归函数如何写呢?请高手指教。

------解决方案--------------------
引用:

function convert(source){
var tmp={},parent,n;
for(n in source){
var item=source[n];
if(item.ID==item.ParentID){
parent=item.ID;
}
if(!tmp[item.ID]){
tmp[item.ID]={};
}
tmp[item.ID].Name=item.Name;
tmp[item.ID].ID=item.ID;
if(!("children" in tmp[item.ID]))tmp[item.ID].children=[];

if(item.ID!=item.ParentID){
if(tmp[item.ParentID]){
tmp[item.ParentID].children.push(tmp[item.ID]);
}
else{
tmp[item.ParentID]={children:[tmp[item.ID]]};
}
}
}
return tmp[parent];
}

写了一个,供参考,将原始JSON数据传入函数即可得到树型数据。

  相关解决方案