jeudi 21 mai 2020

Best pattern to store nested parent-child objects to access bottomToTop & TopToBottom

There is an entity named Category which contains id, name, parent, isLast properties in database.

each category has children if isLast prop is false and category is itself a child if parent prop isn't null.

so far just wanted to show how data is stored in database. now this categories are fetched and must be stored in client side in a way that both top to bottom and bottom to top be available. i mean if a category is given i must be able to see its children and its parent.

i'm looking for a good & efficient data structure to store them.

my current solution is to store all categories in a map like: Map<number, Category> which Category class is like below:

class Category {
    public id: number
    public parent: number
    public name: string
    public children: number[] //IDs of its children
}

this way i have to store all categories in that Map and there is no nesting which i'm not sure is good thing or not. is my solution best suit for here?

is there any best practice or solution to store nesting objects (for more examples: Continents, countries, cities, villages, and so on) to be able to lookup easily is both ways?

Aucun commentaire:

Enregistrer un commentaire