Samuel
Samuel

Reputation: 2442

Recursive Javascript

Given a data structure as follows:

var endpoints = {
    // top level
    "orders": {
        url: "/orders",
        // child
        "sub-level": {
            url: "/sublevel"
        }
    },
    // users
    "users": {
        url: "/users",
        // child
        "another-sublevel": {
            url: "/another-sublevel"
        }
    }
}

How could I recurse over this generating a "Route" object each time I encounter a URL? I also need to track the parents to a route, so:

var Route = function(name, url, parents) {
}

Where name is the key (e.g. "orders" or "users" in the top level) url is obvious and "parents" is some sort of stack that's generated as we drill down each level.

I've had a couple of goes at writing this and I'm running into trouble with variable scope / passing attributes by reference vs. value and all sorts of other weirdness.

The data structure is not fixed either, but needs to contain that information.

Upvotes: 3

Views: 2058

Answers (2)

gnab
gnab

Reputation: 9561

The following code will map the data structure into a list of Route objects, each containing the belonging name, url and list of parents:

function mapRoutes(endpoints, parents, routes) {
  var name, url;

  for (name in endpoints) {
    if (!endpoints.hasOwnProperty(name) || name === 'url') {
      continue;
    }   

    url = endpoints[name]['url'];

    routes.push(new Route(name, url, parents));

    mapRoutes(endpoints[name], parents.concat([name]), routes);
  }

  return routes;
}

var routes = mapRoutes(endpoints, [], []);

Upvotes: 0

Mic
Mic

Reputation: 25154

Here's an example

   function recurse(obj, parents){
        var prop;
        parents = parents || [];
        for(prop in obj){
            if(typeof(obj[prop]) === 'string' && prop === 'url'){
                //do something with url
                console.log(obj[prop], parents.join('->'));
            }else{
                parents.push(prop);
                recurse(obj[prop], parents);
                parents = [];
            }
        }
    }

    recurse(endpoints);

Upvotes: 2

Related Questions