I have a JSON array containing objects that are not structured hierarchically, but have have one-to-many relationships, similar to example below:
[
{"id": 1, "parentId": 5},
{"id": 2, "parentId": 1},
{"id": 3, "parentId": 1},
{"id": 4, "parentId": 3},
{"id": 5, "parentId": 3},
{"id": 6, "parentId": 2},
{"id": 7, "parentId": 4},
{"id": 8, "parentId": 2}
]
I'd like to use AngularJS to show this data in a html table in a way that shows hierarchy of objects, beginning from selected one. If we wanted to show hierarchy for object with "id": 1
, then it should produce view similar to this (up to bottom):
{"id": 1}
{"id": 2} {"id": 3}
{"id": 6} {"id": 8} {"id": 4} {"id": 5}
{"id": 7}
I've built an Angular service to give me all child objects of the selected ID, but I don't know how can I loop (recursively?) through this array to produce the desired effect.
I thought it could be done with recursive templates, but all of the examples I've found are based on data/json already structured hierarchically. I've also tried to nest ng-repeat
directives but then I would have to nest as many ng-repeat
s as many levels there would be. I also thought about transforming the whole array to another that would have relationships built-in, but that doesn't seem very efficient.
In vanilla javascript I would make a function that would recursively search for every child of object and if found, simply append it to the DOM.
What is "angular way" of achieving this? I really have no clue where to go next.
EDIT:
I should've explicitly state, that IDs of elements are looped, so there should be condition set to stop when selected ID is found again. In example above that would be empty field under element with ID 5, even though {"id": 1, "parentId": 5}