I am using AngularJS and am in my controller. I have my $scope.tree variable to hold a simple JSON object. I am trying to build a nested tree and the data is coming from several rest calls.
After my first REST call, I successfully have my initial $scope.tree object:
[
{"name":"Item 1 Name","id":"1","parentid":"","children":[]},
{"name":"Item 2 Name","id":"2","parentid":"","children":[]}
]
I make a second REST call and have 2 elements returned:
{"name":"Item 3 Name","id":"3","parentid":"2","children":[]},
{"name":"Item 4 Name","id":"4","parentid":"2","children":[]}
and I want to add these as appropriate children to the first call to end up with:
[
{"name":"Item 1 Name","id":"1","children":[]},
{"name":"Item 2 Name","id":"2","children":[
{"name":"Item 3 Name","id":"3","parentid":"2","children":[]},
{"name":"Item 4 Name","id":"4","parentid":"2","children":[]}
]}
]
A third call:
{"name":"Item 5 Name","id":"5","parentid":"3","children":[]},
{"name":"Item 6 Name","id":"6","parentid":"4","children":[]}
And end up with:
[
{"name":"Item 1 Name","id":"1","children":[]},
{"name":"Item 2 Name","id":"2","children":[
{"name":"Item 3 Name","id":"3","parentid":"2","children":[
{"name":"Item 5 Name","id":"5","parentid":"3","children":[]}
]},
{"name":"Item 4 Name","id":"4","parentid":"2","children":[
{"name":"Item 6 Name","id":"6","parentid":"4","children":[]}
]}
]}
]
In my controller I have something like:
$scope.tree = {};
$scope.restcall1 = (results of restcall)
$scope.restcall2 = (results of restcall)
$scope.restcall3 = (results of restcall)
$scope.tree = $scope.restcall1;
now I need to join $scope.restcall1 and $scope.restcall2 so I built a treeBuilder service, with an addCall2 method.
$scope.tree = treeBuilder.addBranch($scope.tree, $scope.$restcall1);
In treeBuilder service:
addBranch: function(branch, tree){
for (var i=0; i<branch.length; i++){
network = _.filter(tree, function(obj){
if(obj.id == branch[i].parentId){
obj.children.push(branch[i]);
}
});
}
return tree;
},
obj.children.push(new_branch); doesnt work, and I have tried 10 other ways - I am finding the parent object just fine but can't find a way to add the branch to the parent.children. As you see above, I have underscore available to me if that helps.
Thanks!