[英]Create Parent-Child tree JSON with IDs not following each other
I'm trying to create a tree with database records, at first I used the following code : 我试图用数据库记录创建树,起初我使用以下代码:
Create Parent-Child tree JSON 创建父子树JSON
Which worked fine, but since I can Insert and Delete nodes of the tree in my database, the function isn't working anymore. 效果很好,但是由于我可以在数据库中插入和删除树的节点,因此该功能不再起作用。 As you can see, now I can have the first Element with for Id 90 and childrens width smaller Ids. 如您所见,现在我可以拥有第一个元素,其ID为90,儿童宽度较小的ID。
var arry = [{
"parentId": null,
"moduleId": 90
},
{
"parentId": 1,
"moduleId":65
},
{
"parentId": 1,
"moduleId": 91
},
{
"parentId": 65,
"moduleId": 66
},
{
"parentId": 66,
"moduleId": 79
},
{
"parentId": 90,
"moduleId": 1
}
];
fiddle: https://jsfiddle.net/1c20hb7w/ 小提琴: https : //jsfiddle.net/1c20hb7w/
Of course, I can't change IDs in my database (It would be too simple). 当然,我不能更改数据库中的ID(这太简单了)。 So I would like to know how to makes everything work, if you have a track to help me.. thanks in advance! 因此,如果您有帮助我的话,我想知道如何使所有工作正常。
For a more complicated tree I'd suggest a recursive approach, as example: 对于更复杂的树,我建议采用递归方法,例如:
var arry=[{parentId:null,moduleId:90},{parentId:1,moduleId:65},{parentId:1,moduleId:91},{parentId:65,moduleId:66},{parentId:66,moduleId:79},{parentId:90,moduleId:1}]; function recursiveTree(array) { function getChildren(parents, input) { return parents.map(parent => { const children = input.filter(x => x.parentId === parent.moduleId); parent.children = children; if(children.length === 0) { return parent; } else { parent.children = getChildren(children, input); return parent; } }) } const roots = array.filter(x => x.parentId === null); return getChildren(roots, array); } var r = recursiveTree(arry) console.log('array', r); console.log('result', JSON.stringify(r))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.