-1

I would like to generate tree structure from following data:

[
{"first_name" => "Test", "id" => "1", "parent_id" => ""},
{"first_name" => "Test1", "id" => "2", "parent_id" => "1"},
{"first_name" => "Test2", "id" => "3", "parent_id" => "1"},
{"first_name" => "Test3", "id" => "4", "parent_id" => "2"}
]

I would like to create ruby script to build following structure:

[
{ 
  "first_name" => "Test", 
  "id" => "1",
  "children" => [
    {
     "first_name" => "Test1", 
     "id" => "2",
     "children" => [
       {
        "first_name" => "Test3", 
        "id" => "4"
       }
     ]
    },
    {
      "first_name" => "Test2", 
      "id" => "3"
    }
}
] 

Do you have some tips in this case?

1

1 Answer 1

1

Given a particular node, it is easy to find that node's children. The key is to do it in the right order and to not repeat anything. So you can start at the roots and separate the nodes into two sets: nodes which have been added to a tree, and nodes which have not. Then just iterate through nodes in a tree, add their children, and move the children from the set of nodes not in a tree to the set of nodes in a tree.

I can add some Ruby code later, but right now it's not clear to me what you need it for.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.