I am trying to create a function that will loop over a Hierarchy of arrays and concat them together. I am struggling to think of a way to do this.

I call a Web API that returns me some data which has the same properties and layout but can differ in how many Hierarchy layer array there is.

**Folders: A folder can contain 'Routes' but can also contain another folder inside of it which can then also contain more 'Routes' etc**

**Routes: A single object which is a route.**

For example:

```
{
   "id":1,
   "folders":[
      {
         "id":2,
         "folders":[
            {
               "id":3,
               "folders":[],
               "routes":[]
            }
         ],
         "routes":[
            {
               "id":1002,
               "name":"Route3"
            },
            {
               "id":1003,
               "name":"Route4"
            }
         ]
      }
   ],
   "routes":[
      {
         "id":1000,
         "name":"Route1"
      },
      {
         "id":1001,
         "name":"Route2"
      }
   ]
}

```

I need to be able to keep going deeper into the hierarchy and concat all of the Routes arrays with the Folders array, so I can bind the Kendo TreeView with a single child which will be the Folders array.

So far I have tried:

```
for (var i = 0; i < Folders.length; i++) {
    if (Folder[i].Folders.length > 0) {
        for (var e = 0; e < Folder[i].Folder[e].length; e++) {
            if (Folder[i].Folders[e].length > 0) {
                ...
            }
        }
    }
}

```

The problem with that method is that I will never know how many layer there will be and therefore is not a viable method.

The result I need is the above example to look like:

```
{
   "id":1,
   "folders":[
      {
         "id":2,
         "folders":[
            {
               "id":3,
               "folders":[

               ],
               "routes":[

               ]
            },
            {
               "id":1002,
               "name":"Route3"
            },
            {
               "id":1003,
               "name":"Route4"
            }
         ]
      },
      {
         "id":1000,
         "name":"Route1"
      },
      {
         "id":1001,
         "name":"Route2"
      }
   ]
}

```