使用nodejs构build多级菜单

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

在这里输入图像描述

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中的类别。

下面的例子展示了一种做你想做的事的方法。

 // 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))); 
Interesting Posts