0

I am trying to write a recursive function in JavaScript. My function needs to search a tree of items. I have created a JSFiddle. When I run the JavaScript in Chrome, I get an error that says:

RangeError: Maximum call stack size exceeded

I assume this means that I'm not returning my value at the correct time. However, I continue to review the function and it looks correct to me. What am I doing wrong?

var sitemap = [
  {
    name: 'dashboards', children: [
      { name: 'dashboard 1', route: '/dashboards/dashboard1', html: '' }
    ]
  },
  {
    name: 'objects', children: [
      { name: 'players', route: '/objects/players', html: '/objects/players.html' },
      { name: 'teams', route: '/objects/teams', html: '/objects/teams.html' },
      { name: 'coaches', route: '/objects/coaches', html: '/objects/coaches.html' },
      { name: 'cities', children: [
        { name: 'Chicago', route: '/cities/chicago',
                 html: '/objects/cities/chicago.html' },
        { name: 'Philadelphia', route: '/cities/philadelphia', html: '/objects/cities/philadelphia.html' }
]},                    
        ]
    }
];

var getFromSitemap = function (path, entries) {
    var sitemapItem = null;
    if (entries) {
        angular.forEach(sitemap, function (entry, key) {
            if (entry.hasOwnProperty("children")) {
                sitemapItem = getFromSitemap(path, entry.children);
            } else if (entry.route === path) {
                sitemapItem = entry;
            }
        });
    }
    return sitemapItem;
};

    var getItem = function() {    
var item = getFromSitemap('/cities/chicago', sitemap);
console.log(item);      
    }

Thank you!

3
  • What's your function? Commented Feb 26, 2014 at 21:27
  • 2
    You should post your code here. Also, try using the debugger in your browser. Commented Feb 26, 2014 at 21:27
  • I added your code to the question (which is the proper StackOverflow procedure). Commented Feb 26, 2014 at 21:34

1 Answer 1

2

You are calling foreach on the same object (sitemap) everytime:

 angular.forEach(sitemap, function ...

It seems like you want to be calling it on entries recursively

 angular.forEach(entries, function ....
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.