So I needed to create a tree component from a flat array recently. It took me sometime to put it together so I decided to share my code with you.
A flat array is an array of objects where a property on the object refers to id of another one and that’s how we can create association between objects. Imagine an array, lets call it search results array, where there is a property called “menuId” which is a unique identifier for the object and another property called “parentMenuId” which refers to menuId number of parent object. Below image is an illustration of a simple flat array objects.
by assigning a menuId to parentMenuId property of an object, we can assign a parent to the object. so even though there is no indication of tree structure in the data model, we can visualize a hierarchic relationship between objects.
so we need to create a data model that represents this relationship.
Class tree includes id and parentId of the type of string (could be number as well) and a URL property to redirect users when they click on tree node.
I have created and example on code on github that you download here
you can view the example on stackblitz here: