简体   繁体   中英

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

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.

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/

Of course, I can't change IDs in my database (It would be too simple). 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)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM