使用nodejs构建多级菜单

时间:2016-04-23 11:50:55

标签: node.js mongodb categories hierarchy

我目前在我的数据库中有以下数据

enter image description here

Mongo数据库存储如下

id parent
1  0
2  0
3  1
4  1
5  2
6  2
7  2
30 3
31 3
70 7
71 7

现在我希望使用nodejs

在单个javascript数组中输出
[
{id:1,sub:[
  {id:3, sub:[{id:30},{id:31}]}, 
  {id:4,sub:[]}
] 
}, 
{id:2,sub:[
  {id:5,sub: []},
  {id:6,sub: []},
  {id:7,sub: [{id:70}, {id:71}]}
  ] 
}
]

这样做的目的基本上是以megamenu输出类别。

1 个答案:

答案 0 :(得分:0)

以下示例显示了执行所需操作的方法。



// Example data from the question
var nodes = [
    { id: 1, parent: 0 },
    { id: 2, parent: 0 },
    { id: 3, parent: 1 },
    { id: 4, parent: 1 },
    { id: 5, parent: 2 },
    { id: 6, parent: 2 },
    { id: 7, parent: 2 },
    { id: 30, parent: 3 },
    { id: 31, parent: 3 },
    { id: 70, parent: 7 },
    { id: 71, parent: 7 }
];

// We construct `t`, the array of parents, so that `t[i] === x` means that `x`
// is the parent of `i`
var t = [];
for (var i = 0; i < nodes.length; i++) {
    t[nodes[i].id] = nodes[i].parent;
}

// `t` represents the array of parents
// `c` represents the parent whose children should be put in the outputted array
function f(t, c) {
    // The output structure
    var a = [];

    // We loop through all the nodes to fill `a`
    for (var i = 0; i < t.length; i++) {
        // If the node has the parent `c`
        if (t[i] === c) {
            // Create an object with the `id` and `sub` properties and push it
            // to the `a` array
            a.push({
                id: i,
                // The `sub` property's value is generated recursively
                sub: f(t, i)
            });
        }
    }

    // Finish by returning the `a` array
    return a;
}

// Print the outputted array in a pretty way
// We call the `f` function with the 0 parameter because 0 is the parent of the
// nodes that should be directly put in the returned array
alert(JSON.stringify(f(t, 0)));
&#13;
&#13;
&#13;

在Node.js 0.12.13上运行此代码而不是上述代码段末尾的alert

var util = require('util');
console.log(util.inspect(f(t, 0), {
    colors: true,
    depth: null
}));

打印以下内容:

[ { id: 1,
    sub: 
     [ { id: 3, sub: [ { id: 30, sub: [] }, { id: 31, sub: [] } ] },
       { id: 4, sub: [] } ] },
  { id: 2,
    sub: 
     [ { id: 5, sub: [] },
       { id: 6, sub: [] },
       { id: 7, sub: [ { id: 70, sub: [] }, { id: 71, sub: [] } ] } ] } ]

我认为这就是你想要的。

我还阅读this page,其中描述了另一种可能更有效的解决方案。