在我的 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
中找到。节点 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;
}
关于javascript - 需要将复杂的json obj转换为合适的angularjs ui树数据json结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39392217/