Reputation: 1863
In my angularjs project I have original json in the following format :
$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"
}
]
}
Now I want to convert orgJsonObj
json structure in to the tree structure similar to angular ui tree json data structure. In orgJsonObj
, parentNodesList
contains all parents in the tree. Each parent's children list is available in childNodes
. Each nodes complete information is available in nodeDetailsList
. The node obj { "id":"0", "name":"node0"}
does not have parentId
, property in it because it is the root of the tree.
After conversion my $scope.orgJsonObj
, should become as shown below (which is suitable for angularjs ui tree)
$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":[
]
}
]
}
]
}
]
}
]
Can any one help me in this.
Upvotes: 0
Views: 347
Reputation: 1577
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;
}
Upvotes: 1