gpt4 book ai didi

node.js - 使用nodejs构建多级菜单

转载 作者:太空宇宙 更新时间:2023-11-03 22:13:01 25 4
gpt4 key购买 nike

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

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

最佳答案

以下示例展示了一种执行您想要的操作的方法。

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

在 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其中描述了另一种可能更有效的解决方案。

关于node.js - 使用nodejs构建多级菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36810428/

25 4 0