Java递归实现的一个数据转换,跟前台JavaScript比较起来,还是使用JavaScript比较好,比较一旦数据中的上下级节点如果存在错误的结构可能会导致死循环,最终直接出现递归溢出的问题,影响服务器正常运行,而这种逻辑放在前台比较起来影响的范围就小许多了,故本文将前一篇的使用Java实现又改造成使用JavaScript实现,参考如下数据所示:
[
{ "id": 1, "name": "北京市", "parentId": -1 },
{ "id": 2, "name": "海淀区", "parentId": 1 },
{ "id": 3, "name": "朝阳区", "parentId": 1 },
{ "id": 4, "name": "湖北省", "parentId": -1 },
{ "id": 5, "name": "武汉市", "parentId": 4 },
{ "id": 6, "name": "襄阳市", "parentId": 4 },
{ "id": 7, "name": "襄城区", "parentId": 6 },
{ "id": 8, "name": "襄州区", "parentId": 6 },
{ "id": 9, "name": "樊城区", "parentId": 6 },
{ "id": 10, "name": "老河口市", "parentId": 6 },
{ "id": 11, "name": "谷城县", "parentId": 6 },
{ "id": 12, "name": "南漳县", "parentId": 6 },
{ "id": 13, "name": "枣阳市", "parentId": 6},
{ "id": 14, "name": "保康县", "parentId": 6 },
{ "id": 15, "name": "宜城市", "parentId": 6 }
]
[
{
"nodeId": 1,
"nodes": [
{
"nodeId": 2,
"text": "海淀区"
},
{
"nodeId": 3,
"text": "朝阳区"
}
],
"text": "北京市"
},
{
"nodeId": 4,
"nodes": [
{
"nodeId": 5,
"text": "武汉市"
},
{
"nodeId": 6,
"nodes": [
{
"nodeId": 7,
"text": "襄城区"
},
{
"nodeId": 8,
"text": "襄州区"
},
{
"nodeId": 9,
"text": "樊城区"
},
{
"nodeId": 10,
"text": "老河口市"
},
{
"nodeId": 11,
"text": "谷城县"
},
{
"nodeId": 12,
"text": "南漳县"
},
{
"nodeId": 13,
"text": "枣阳市"
},
{
"nodeId": 14,
"text": "保康县"
},
{
"nodeId": 15,
"text": "宜城市"
}
],
"text": "襄阳市"
}
],
"text": "湖北省"
}
]
function convertData(){
var datas = [
{"id":1,"name":"北京市","parentId":-1},
{"id":2,"name":"海淀区","parentId":1},
{"id":3,"name":"朝阳区","parentId":1},
{"id":4,"name":"湖北省","parentId":-1},
{"id":5,"name":"武汉市","parentId":4},
{"id":6,"name":"襄阳市","parentId":4},
{"id":7,"name":"襄城区","parentId":6},
{"id":8,"name":"襄州区","parentId":6},
{"id":9,"name":"樊城区","parentId":6},
{"id":10,"name":"老河口市","parentId":6},
{"id":11,"name":"谷城县","parentId":6},
{"id":12,"name":"南漳县","parentId":6},
{"id":13,"name":"枣阳市","parentId":6},
{"id":14,"name":"保康县","parentId":6},
{"id":15,"name":"宜城市","parentId":6}
];
var treeviews = convertTreeview(datas);
for (var i=0 , lens = treeviews.length ; i < lens ; i++){
var treeview = treeviews[i];
collectList(treeview , datas);
}
return treeviews;
}
function collectList(treeview , datas){
var nodeId = treeview.nodeId;
for (var i=0 , lens = datas.length ; i < lens ; i++) {
var data = datas[i];
var parentId = data.parentId;
if(parentId != null && parentId === nodeId){
if(treeview.nodes == null){
treeview.nodes = [];
}
var childMenuTreeview = {"nodeId" : data.id , "text": data.name , state: null , nodes: null};
treeview.nodes.push(childMenuTreeview);
this.collectList(childMenuTreeview , datas);
}
}
}
function convertTreeview(datas){
var data = [];
for (var i=0 , lens = datas.length ; i < lens ; i++){
var item = datas[i];
if(item.parentId === -1){
var treeview = {"nodeId": item.id , "text": item.name , state: null , "nodes": null};
data.push(treeview);
}
}
return data;
}