在javascript中进行树遍历

log*_*kal 2 javascript nested-sets mongodb node.js

我正在尝试为节点中的MongoDB中存储的页面生成URL.

使用以下函数,我想遍历一个javascript对象,并显示每个元素的路径.

我几乎在那里,但我被卡住了 - 使用Async甚至可能有更好的方法来做到这一点(我必须承认,让我有点困惑).

功能:( 演示)

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 + "/");
                }
            }
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

输出:

/michael/
/michael/angela/oscar
/michael/meredith/creed
/michael/meredith/creed/kelly
Run Code Online (Sandbox Code Playgroud)

预期产出:

/michael/
/michael/angela/
/michael/angela/oscar/
/michael/meredith/
/michael/meredith/creed/
/michael/meredith/kelly/
Run Code Online (Sandbox Code Playgroud)

宾语:

[
  {
    "name": "michael",
    ...
    "children": [
      {
        "name": "angela",
        ...
        "children": [
          {
            "name": "oscar",
            ...
            "children": []
          }
        ]
      },
      {
        "name": "meredith",
        ...
        "children": [
          {
            "name": "creed",
            ...
            "children": []
          },
          {
            "name": "kelly",
            ...
            "children": []
          }
        ]
      },
      { ... }
    ]
  }
]
Run Code Online (Sandbox Code Playgroud)

如果有帮助,则使用嵌套集存储数据:https://github.com/groupdock/mongoose-nested-set 因此,使用嵌套集可能有更好的方法来执行上述工作(否定上述对象).

bio*_*all 5

干得好.你不需要第二个for循环,因为你的printTree函数无论如何都会循环遍历所有(演示).

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 + '/')
    }
  }
}
Run Code Online (Sandbox Code Playgroud)