Creating tree from flat array in Angular


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.

export class Tree {
  id: string;
  parentId?: string;
  name: string;
  url: string;
  children?: Tree[];
  isExpanded?: boolean;
}

I have created and example on code on github that you

download here
https://github.com/ramin-ahmadi/Flat-Tree

you can view the example on stackblitz here:
https://stackblitz.com/github/ramin-ahmadi/Flat-Tree

Ramin Ahmadi
I am a full-stack front end developer with over 5 years experience in web design and development. I have worked with a wide variety of environments and languages including Angular, TypeScript, NodeJS, Restful API, Microservices, Atomic design, JQuery, Material design, Progressive Web Apps, DevOps, and many Azure tools. I make it a goal to automate myself out of routine tasks in my daily work. My motto is, ‘write human readable code, lean and clean’.

Comments 0

Your email address will not be published. Required fields are marked *

Creating tree from flat array in Angular

log in

Captcha!

reset password

Back to
log in
Font Resize
Choose A Format
Trivia quiz
Series of questions with right and wrong answers that intends to check knowledge
Poll
Voting to make decisions or determine opinions
List
The Classic Internet Listicles
Image
Photo or GIF
Gif
GIF format