我有一个看起来像的对象:
{
api: {
test: function () {}
},
routes: {
docs: {
options: function () {},
usage: function () {}
},
index: function () {},
bugs: {
report: function () {}
}
}
}
这是一个通过遍历目录树并要求目录中的每个文件(如果有文件)来映射我的应用程序控制器的对象。该文件返回一个module.exports
函数。
我想要做的是在快递中有以下路由:
application.get("/", controllers.routes.index);
application.get("/partials/index", controllers.routes.partials.index);
application.get("/partials/documentation/amd", controllers.routes.partials.documentation.amd);
application.get("/partials/documentation/api", controllers.routes.partials.documentation.api);
application.get("/partials/documentation/jquery", controllers.routes.partials.documentation.jquery);
application.get("/partials/documentation/options", controllers.routes.partials.documentation.options);
application.get("/partials/documentation/usage", controllers.routes.partials.documentation.usage);
application.get("/partials/installation/bower", controllers.routes.partials.installation.bower);
application.get("/partials/installation/source", controllers.routes.partials.installation.source);
application.get("/partials/compatibility/methods", controllers.routes.partials.compatibility.methods);
application.get("/partials/compatibility/support", controllers.routes.partials.compatibility.support);
application.get("/partials/bugs/requests", controllers.routes.partials.bugs.requests);
application.get("/partials/bugs/report", controllers.routes.partials.bugs.report);
application.get("*", controllers.routes.index);
以某种方式动态而不是对每一个进行硬编码。我无法弄清楚这样做的逻辑,我正在考虑做类似的事情:
var keys = Object.keys(controllers), //where controllers is my object containing the routes and api, what I just wrote one block of code above
length = keys.length - 1;
while (length >= 0) {
... something that will check the object if it will contain any other object and will do a recursive iteration, then will somehow concatenate the parent object keys ...
}
我不确定如何获取子对象的所有父键(类似于routes docs options
),因为这是我实际上需要组成传递给 express 的路由字符串。