急急急!!!怎样将json数组数据 转成json树结构数据?
现有数据:{success:true,root:[{id:"001",name:"aaa",parent:null},{id:"002",name:"bbb",paren...
现有数据:
{success:true,root:[
{id:"001",name:"aaa",parent:null},
{id:"002",name:"bbb",parent:null},
{id:"003",name:"ccc",parent:"001"},
{id:"004",name:"ddd",parent:"001"},
{id:"005",name:"eee",parent:"002"},
{id:"006",name:"fff",parent:"003"}
]}
怎样将上面的数据转成如下的格式:
{success:true,root:[
{id:"001",name:"aaa",text:"aaa",leaf:false,children:[
{id:"003",name:"ccc",text:"ccc",leaf:false,children:[
{id:"006",name:"fff",text:"fff",leaf:true}
]},
{id:"004",name:"ddd",text:"ddd",leaf:true}
]},
{id:"002",name:"bbb",text:"bbb",leaf:false,children:[
{id:"005",name:"eee",text:"eee",leaf:true}
]}
]}
树结构如下图: 展开
{success:true,root:[
{id:"001",name:"aaa",parent:null},
{id:"002",name:"bbb",parent:null},
{id:"003",name:"ccc",parent:"001"},
{id:"004",name:"ddd",parent:"001"},
{id:"005",name:"eee",parent:"002"},
{id:"006",name:"fff",parent:"003"}
]}
怎样将上面的数据转成如下的格式:
{success:true,root:[
{id:"001",name:"aaa",text:"aaa",leaf:false,children:[
{id:"003",name:"ccc",text:"ccc",leaf:false,children:[
{id:"006",name:"fff",text:"fff",leaf:true}
]},
{id:"004",name:"ddd",text:"ddd",leaf:true}
]},
{id:"002",name:"bbb",text:"bbb",leaf:false,children:[
{id:"005",name:"eee",text:"eee",leaf:true}
]}
]}
树结构如下图: 展开
1个回答
展开全部
<html>
<head>
<meta charset="utf-8" />
<title>b.html</title>
<style type="text/css">
</style>
<script type="text/javascript">
var jsonobj =
{
success : true,
root : [
{
id : "001",
name : "aaa",
parent : null
},
{
id : "002",
name : "bbb",
parent : null
},
{
id : "003",
name : "ccc",
parent : "001"
},
{
id : "004",
name : "ddd",
parent : "001"
},
{
id : "005",
name : "eee",
parent : "002"
},
{
id : "006",
name : "fff",
parent : "003"
}
]
};
var convert = function (jsonobj)
{
var result = {};
for ( var p in jsonobj)
{
if (p != 'root')
{
result[p] = jsonobj[p];
}
}
result.root = [];
var root = jsonobj.root;
for ( var i = 0; i < root.length; i++)
{
var ri = root[i];
ri.text = ri.name;
for ( var j = 0; j < root.length; j++)
{
root[j].leaf = true;
for ( var k = 0; k < root.length; k++)
{
if (root[k].parent == root[j].id)
{
root[j].leaf = false;
break;
}
}
}
if (ri.parent != null && ri.parent != 'null')
{
for ( var j = 0; j < root.length; j++)
{
var rj = root[j];
if (rj.id == ri.parent)
{
rj.children = !rj.children ? [] : rj.children;
rj.children.push (ri);
break;
}
}
}
if (ri.parent == null || ri.parent == 'null')
{
result.root.push (ri);
}
}
return result;
}
var result = convert (jsonobj);
console.log (result);
</script>
</head>
<body>
</body>
</html>
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询