I have JSON document which has some nested arrays. And I want to make function AAA() which recalls every time if an array has nested array. And then stop when there isn’t more nested arrays.
For example. If I have:
array[AAA,BBB,CCC]
|
AAA[AAA,BBB,CCC]
|
AAA[AAA,BBB,CCC]
|
etc.
I want to call function AAA() always when AAA has a subarray. Let’s say AAA has 5 times subAAA. I want the function(AAA) to call itself 5 times and then stop. And if in future I add more subarrays to call more times.
If it will help here is my .json:
{
"navigation" : [
{
"name" : "home",
"href" : "home.html"
},
{
"name" : "services",
"href" : "interior.html",
"navigation" : [
{
"name" : "PROJECT MANAGEMENT",
"href" : "interior.html",
"navigation" : [
{
"name" : "PROJECT MANAGEMENT",
"href" : "interior.html"
},
{
"name" : "BUSINESS ANALYST",
"href" : "interior.html"
}
]
},
{
"name" : "BUSINESS ANALYST",
"href" : "interior.html"
}
]
},
{
"name" : "company",
"href" : "home.html"
}
]
}
And the js code is:
function parseJSON(){
var navigation = new_json['navigation'];
var nav_html = '';
for (var i = 0; i < navigation.length; i++) {
var name = navigation[i]['name'];
var href = navigation[i]['href'];
var submenu = navigation[i]['navigation'];
nav_html += '<li><a href="' + href + '">' + name + '<span class="ddArrow"></span></a>';
if( typeof(submenu) != 'undefined' ){
nav_html += '<ul>';
for( var j=0; j<submenu.length; j++ ){
var submenu_name = submenu[j]['name'];
var submenu_href = submenu[j]['href'];
nav_html += '<li><a href="' + submenu_href + '">' + submenu_name + '</a></li>';
}
nav_html += '</ul>';
}
nav_html += '</li>';
console.log( nav_html );
$('#navigation ul').html( nav_html );
};
};
That way I want to create navigation which has submenus. Now I have 3 levels, but if I decide to add 4th and 5th. I want my code to parse them in the HTML without writing more code. I have the rest … I just need to the IF when function stops.
I simply don’t write what I have tried because I understand why is not working.
A recursive function is quite simple to build, and is very similar to the code you already have: