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, [], []);
精彩评论