急急急!!!怎样将json数组数据 转成json树结构数据?
发布网友
发布时间:2022-04-24 17:16
我来回答
共1个回答
热心网友
时间:2023-10-25 09:50
<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>