Mark
Mark

Reputation: 3197

iterating through array of nested objects with javascript/lodash

I have an array of objects that represents a nested navigation list.

[
    {
        name: 'one',
        link: 'blah/blah',
        pages: [
            {
               name: 'one A'
               link: 'blah/blah',
               pages: []
            },
            {
               name: 'one B'
               link: 'blah/blah',
               pages: []
            },
            {
               name: 'one C'
               link: null,
               pages: [
                   {
                       name: 'one C I'
                       link: 'blah/blah',
                       pages: []
                   }
               ]
            }
        ]
    } 
]

The first level of objects can have a link and pages the nested objects will either have a link or pages. I can't assume a limit to the depth of the nesting. I need an object for each state that includes its name, its link if it exists and all of its parents. My current solution does not account for deeper than 3 levels of nesting and adding support for each layer is laborious.

I also need to be able to search the resulting array of objects to get their link later on if that makes a difference to the solution.

I need a javascript solution but can also (and would like to) use the functions contained in the lodash library

Upvotes: 3

Views: 17686

Answers (1)

Trace
Trace

Reputation: 18869

Here is a way to loop through the array recursively:

http://jsfiddle.net/yLnZe/37/

var arrPages = [{
        name: 'one',
        link: 'blah/blah',
        pages: [{
               name: 'one A', 
               link: 'blah/blah',
               pages: []
            },
            {
               name: 'one B', 
               link: 'blah/blah',
               pages: []
            },
            {
               name: 'one C', 
               link: null,
               pages: [{
                       name: 'one C I', 
                       link: 'blah blah',
                       pages: []
                   }]
            }]
    }]; 

function recursiveFunction(collection){ 
    _.each(collection, function(model){ 
        console.log(model); 
        if(model.pages.length > 0){ 
            recursiveFunction(model.pages); 
        }
    }); 
}; 

recursiveFunction(arrPages); 

Is this what you need, or do you need anything more specifically? Based on your last comments, I'm a bit confused if you need anything else.

Upvotes: 13

Related Questions