我正在尝试为节点中存储在MongoDB中的页面生成URL。在树中遍历javascript
使用下面的函数我想遍历一个javascript对象并显示每个元素的路径。
我快要到了,但我被卡住了 - 甚至可能有更好的方法来使用异步(我必须承认,让我有点困惑)做到这一点。
功能:(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 所以有可能是一个更好的办法做到使用嵌套组(否定了上述目的)以上工作。
你绝对钉它! http://jsfiddle.net/cT8wn/2/ –
嗨,这适用于迈克尔,安吉拉和奥斯卡,但是一旦树到达迈克尔的其他孩子,它就会破裂。 [见demo](http://jsfiddle.net/WHZUE/)meredith是angela的兄弟姐妹,但输出显示meredith是angela的孩子。 – logikal
这是因为这一行:'slug = slug + people [i] .name +'/';'为你解决 –