Skip to content Skip to sidebar Skip to footer

Recursive Function To Stop When N-th Nested Array Has No More Nested Arrays

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 nest

Solution 1:

A recursive function is quite simple to build, and is very similar to the code you already have:

function parseJSON() {
    function makeList(navigation) {
        var nav_html = '';
        for (var i = 0; i < navigation.length; i++) {
            var name = navigation[i]['name'],
                href = navigation[i]['href'],
                submenu = navigation[i]['navigation'];

            nav_html += '<li><a href="' + href + '">' + name + '<span class="ddArrow"></span></a>';     

            if( typeof(submenu) != 'undefined' ){
                nav_html += '<ul>';
                // now here, do not iterate it again!
                // call the function recursively!
                nav_html += makeList(submenu);
                nav_html += '</ul>';
            }
            nav_html += '</li>';
        }
        return nav_html;
    }
    $('#navigation ul').html( makeList( new_json['navigation'] ) );
}

Solution 2:

If I'm right in thinking that it only needs to run again if it contains a navigation property, you could just use:

// Without using Array.forEach. Array.isArray polyfill may be 
// required to support older browsers.
function getLinks(obj) {
    var i, len;
    if (Array.isArray(obj.navigation)) {
        len = obj.navigation.length;
        for (i = 0; i < len; i += 1) {
            getLinks(obj.navigation[i]);
        }
    }
}

// Using Array.forEach - Polyfill may be required using the 
// forEach method to support older browsers.
function getLinks(obj) {
    if (Array.isArray(obj.navigation)) {
        obj.navigation.forEach(function (link) {
            getLinks(link);
        });
    }
}

// Array.isArray polyfill.
if(!Array.isArray) {
    Array.isArray = function (vArg) {
        return Object.prototype.toString.call(vArg) === "[object Array]";
    };
}

// Array.forEach polyfill.
if (!Array.prototype.forEach) {
    Array.prototype.forEach = function(fn, scope) {
        for(var i = 0, len = this.length; i < len; ++i) {
            fn.call(scope, this[i], i, this);
        }
    }
}

isArray polyfill
forEach polyfill


Post a Comment for "Recursive Function To Stop When N-th Nested Array Has No More Nested Arrays"