开发者

Recursive Javascript

Given a data structure as follows:

var endpoints = {
    // top level
    "orders": {
        url: "/orders",
        // child
        "sub-level": {
            url: "/sublev开发者_开发知识库el"
        }
    },
    // 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.


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);


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, [], []);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜