我正在尝试为存储在 Node 中 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 因此,可能有更好的方法使用嵌套集(否定上述对象)来完成上述工作。
最佳答案
给你。您不需要第二个 for
循环,因为您的 printTree
函数无论如何都会遍历所有内容 (demo)。
function printTree(people, slug){
slug = slug || '/';
for(var i = 0; i < people.length; i++) {
console.log(slug + people[i].name + '/');
if(people[i].children.length){
printTree(people[i].children, slug + people[i].name + '/')
}
}
}
关于javascript - javascript中的树遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21765363/