【发布时间】:2014-02-13 20:58:41
【问题描述】:
我正在尝试为存储在节点中的 MongoDB 中的页面生成 URL。
使用以下函数,我想遍历一个 javascript 对象并显示每个元素的路径。
我快到了,但我被困住了 - 使用 Async 甚至可能有更好的方法来做到这一点(我必须承认,这让我有点困惑)。
函数:(demo)
function printTree(people, slug) {
for (var p = 0; p < people.length; p++) {
var root = people[p];
slug = slug + root.name + "/";
console.log(slug);
if (root.children.length > 0) {
var childrenCount = root.children.length;
for (var c = 0; c < childrenCount; c++) {
if (root.children[c].children.length > 0) {
printTree(root.children[c].children, slug + root.children[c].name + "/");
}
}
}
}
};
输出:
/michael/
/michael/angela/oscar
/michael/meredith/creed
/michael/meredith/creed/kelly
预期输出:
/michael/
/michael/angela/
/michael/angela/oscar/
/michael/meredith/
/michael/meredith/creed/
/michael/meredith/kelly/
对象:
[
{
"name": "michael",
...
"children": [
{
"name": "angela",
...
"children": [
{
"name": "oscar",
...
"children": []
}
]
},
{
"name": "meredith",
...
"children": [
{
"name": "creed",
...
"children": []
},
{
"name": "kelly",
...
"children": []
}
]
},
{ ... }
]
}
]
如果有帮助,数据将使用嵌套集存储:https://github.com/groupdock/mongoose-nested-set 因此,使用嵌套集(否定上述对象)可能有更好的方法来完成上述工作。
【问题讨论】:
标签: javascript node.js mongodb nested-sets