1
[
  {id: 1,
  name: "test 1",
  children: [
               {id: 2,
               name: "test 1-sub",
               children: []}
            ]
}]

Assuming a json array of something like the above where each element may or may not have children, and it can go up to 9 levels deep.

If I want to know where on the tree I am, and be able to go up or down the tree. I know on the way down I can simple go to the index of the selected child element to see them. How would I go back up the tree?

Basically I'm thinking I'll have two elements on the page. The main array that contains on the data, one element to indicate the current array I'm working with.

codes: any = [];
currentCode: any = {};

To make this easier to read and navigate I am only going to display one level of the tree at a time, so main code, with it's child elements below it.

Do I need to store a map of the path I took to get where I am and walk down from the top each time to get to the point I want to be at?

I hope this isn't too confusing.

1 Answer 1

1

Assuming that:

  • Ids are unique
  • You only need to get to the parent and don't really need the whole path

There are two options. If you could change the json or keep a copy of it, you can add a _parent field for each node. If you don't want to do that you can maintain a map for which the keys are the ids and the values are the parent references.

In either way you can populate the extra data by traversing the tree recursively.

Sign up to request clarification or add additional context in comments.

3 Comments

Could you give me an example of the map method? I want to keep all the json locally, and load child nodes as needed. There are 160,000 total, so loading it all is out of the question.
Do you mean the traverse function? Is it ok by you to keep a map for the 160,000 nodes in memory?
I ended up going with a method where I only show the current branch their looking at. I keep an array of everything loaded, and simply show the branch they are currently looking at rather than display the full tree.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.