B
B
Bamp2017-02-05 23:35:59
JavaScript
Bamp, 2017-02-05 23:35:59

Form an object in recursion?

Good day, the task is to connect the menu on the site (by type three view). Decided to use this plugin: https://github.com/jonmiles/bootstrap-treeview. To output data, it needs to create an array of the form:

var tree = [
        {
          text: "Parent 1",
          nodes: [
            {
              text: "Child 1",
              nodes: [
                {
                  text: "Grandchild 1"
                },
                {
                  text: "Grandchild 2"
                }
              ]
            },
            {
              text: "Child 2"
            }
          ]
        },
        {
          text: "Parent 2"
        },
        {
          text: "Parent 3"
        },
        {
          text: "Parent 4"
        },
        {
          text: "Parent 5"
        }
      ];

Wrote this script:
var obj={};
            function getAllCategory(n,obj){
              for(el in data){
                if(data[el]['parent_id'] == n){
                  j = data[el]['id'];
                  obj[el] = {"text":data[el]['name']};
                  getAllCategory(j,obj[el]);
                }
              }
            }
            getAllCategory(0,obj);

Output in the console of the result in the console (on the image)
Please help me to add the function, I can’t understand where to fix the code so that it works as it should5f7db7ea5a5f4737b7846f10dd76de9f.PNG

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Memorivardo, 2017-02-06
@Memorivardo

Something like this should be:
https://jsfiddle.net/2zjbjhr6/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question