Skip to content
Advertisement

Build tree/linked list from a list of Objects

I am trying to build a tree like hierarchy from modules and their respective submodules, each module has a name, data, and a list of its submodules,

JavaScript

With this code I’m able to detect if something is a submodule of something else but I don’t know how I am supposed to form the connections/build the data structure.

My desired output should look something like this:

JavaScript

enter image description here

I tried using Anytree and Treelib to achieve this for an arbitrary amount of modules but I could not come up with a working solution. Although this problem looks simple (might not be) I just can not figure it out.

Cheers!

Advertisement

Answer

Your data structure already represents a hierarchy, but you could also store the reference of a module’s parent, and have a container class Hierarchy with which to facilitate access to functionality.

I would name the class Module with a capital M, and in submodules store references to Module instances instead of strings. The container Hierarchy class could act as a dictionary so to give access to Module instance by their name.

Here is a proposal:

JavaScript

You could build your input much like you did before:

JavaScript

Here are then some examples on how to use this hierarchy:

JavaScript

This will output:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement