javascript - javascript中的树遍历

标签 javascript node.js mongodb nested-sets

我正在尝试为存储在 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/

相关文章:

linux - Linux 服务器上未启用 MongoDB 身份验证

javascript - Unfiltered inside of filtered - 使用两个元素在过滤后的图像中创建一个未过滤的区域

javascript - FireFox 34 中的 "DataCloneError: The object could not be cloned."

javascript - 如何使用 node.js 将图像存储在 mongodb 中?

javascript - 如何在 node.js 生成的 html 中显示变量

javascript - 在 MongoDB 中实现带有转发的 feed

javascript - 为深层嵌套对象构建 promise 链

javascript - 如何在不加载的情况下切换到 getDerivedStateToProps 未定义

node.js - Favicon 未在 express 本地显示

node.js - 如何使用嵌套模式更新 mongodb 中的文档