我想从模型分支中创建类似思维导图的内容,它具有“父”和“子”值。它看起来像:
Branches = [{
children: {},
_id: String,
parent: { type: Schema.Types.ObjectId, ref: 'Branch' }
}]
我希望得到类似的东西:
[
{
"_id": "599c1f79f339dc3991d8250a",
"name": "Robert",
"children": [
{
"_id": "599c1f82f339dc3991d8250b",
"name": "Robert 1",
"parent": "599c1f79f339dc3991d8250a",
"children": [
{
"_id": "599c1f8ff339dc3991d8250c",
"name": "Robert 2",
"parent": "599c1f82f339dc3991d8250b",
"children": [
{
"_id": "599c2b7373a7d43e5205af1f",
"name": "Robert 4",
"parent": "599c1f8ff339dc3991d8250c",
"__v": 0,
"shareholder": [],
"createdDate": "2017-08-22T13:02:43.290Z",
"children": []
}
],
"__v": 0,
"shareholder": [],
"createdDate": "2017-08-22T12:11:59.230Z"
},
{
"_id": "599c1f9df339dc3991d8250d",
"name": "Robert 3",
"parent": "599c1f82f339dc3991d8250b",
"children": [],
"__v": 0,
"shareholder": [],
"createdDate": "2017-08-22T12:12:13.156Z"
}
],
"__v": 0,
"shareholder": [],
"createdDate": "2017-08-22T12:11:46.938Z"
}
],
"__v": 0,
"parent": null,
"shareholder": [],
"createdDate": "2017-08-22T12:11:37.005Z"
}
]“
如果一个对象的值为父“1”,则带有_id的分支:“1”必须让他在子对象内。我现在的代码是:
Branch.find((err, foundedBranches) => {
function createTree(branch) {
function inner(parent) {
return branch.filter(x => x.parent === parent)
.map(x => {
x.children = inner(x._id)
return x
})
}
return inner(null)
}
let formated = createTree(branches)
res.json(formated)
如果您知道我该如何解决,请帮助:/
答案 0 :(得分:0)
这样的事情 - 你会得到每个条目的孩子
// All items from database
const dataFromDatabase = // ...
// For each item, go and look for childrens
const finalMap = dataFromDatabase.map((x) => {
children: this.getChildren(dataFromDatabase, x._id),
_id: x._id,
// ...
});
// Get all children and for theses children go for children aswell (recursive)...
getChildren(all, id) {
return all.reduce((tmp, x) => {
if (x.parent === id) {
return [
...tmp,
{
children: this.getChildren(all, x._id),
_id: x._id,
// ...
},
];
}
return tmp;
}, []);
}
如果您希望条目仅出现一次,则在开始时过滤条目以仅获取头部(条目没有,父级)
dataFromDatabase.filter(x => !x.parent).map((x) => {