[英]need to convert complex json obj to suitable angularjs ui tree data json structure
在我的angularjs项目中,我具有以下格式的原始json:
$scope.orgJsonObj = {
"parentNodesList":[
"0",
"1",
"1.1",
"2",
"2.2"
],
"childNodes":{
"0":[
"1",
"2"
],
"1":[
"1.1",
"1.2"
],
"1.1":[
"1.1.1"
],
"2":[
"2.1",
"2.2"
],
"2.2":[
"2.2.1",
"2.2.3"
]
},
"nodeDetailsList":[
{
"id":"0",
"name":"node0"
},
{
"id":"1",
"name":"node1",
"parentId":"0"
},
{
"id":"2",
"name":"node2",
"parentId":"0"
},
{
"id":"1.1",
"name":"node1.1",
"parentId":"1"
},
{
"id":"1.2",
"name":"node1.2",
"parentId":"1"
},
{
"id":"1.1.1",
"name":"node1.1.1",
"parentId":"1.1"
},
{
"id":"2.1",
"name":"node2.1",
"parentId":"2"
},
{
"id":"2.2",
"name":"node2.2",
"parentId":"2"
},
{
"id":"2.2.1",
"name":"node2.2.1",
"parentId":"2.2"
},
{
"id":"2.2.3",
"name":"node2.2.3",
"parentId":"2.2"
}
]
}
现在我想将orgJsonObj
json结构转换为类似于angular ui tree json数据结构的树结构。 在orgJsonObj
, parentNodesList
包含树中的所有父级。 每个父级的子级列表在childNodes
中都可用。 每个节点的完整信息可在nodeDetailsList
中nodeDetailsList
。 节点obj { "id":"0", "name":"node0"}
在其中没有parentId
属性,因为它是树的根。
转换后,我的$scope.orgJsonObj
应当如下所示(适用于angularjs ui树)
$scope.finalJsonObj = [
{
"id":"0",
"title":"node0",
"nodes":[
{
"id":"1",
"title":"node1",
"nodes":[
{
"id":"1.1",
"title":"node1.1",
"nodes":[
{
"id":"1.1.1",
"title":"node1.1.1",
"nodes":[
]
}
]
},
{
"id":"1.2",
"title":"node1.2",
"nodes":[
]
}
]
},
{
"id":"2",
"title":"node2",
"nodes":[
{
"id":"2.1",
"title":"node2.1",
"nodes":[
]
},
{
"id":"2.2",
"title":"node2.2",
"nodes":[
{
"id":"2.2.1",
"title":"node2.2.1",
"nodes":[
]
},
{
"id":"2.2.3",
"title":"node2.2.3",
"nodes":[
]
}
]
}
]
}
]
}
]
谁能帮我这个忙。
var originalData = {};
var treeData = transformNesting("0", originalData.childNodes);
var result = applyData(treeData, originalData.nodeDetailsList);
function transformNesting(root, nestedData){
var tree = {
id: root,
nodes: nestedData[root] ? nestedData[root].map(function(newRoot){ return transformNesting(newRoot, nestedData)}) : []
};
return tree;
}
function getNodeById(list, id){
return list.filter(function(item){
return item.id === id;
})[0];
}
function applyData(tree, config){
tree.title = getNodeById(config, tree.id).name;
tree.nodes = tree.nodes.map(function(node){return applyData(node, config)});
return tree;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.