Last active
April 20, 2018 07:08
-
-
Save DykiSA/160b4d8b280ac49a251d0db31472df8f to your computer and use it in GitHub Desktop.
Create recrursive tree from relational data source
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let d = [{ | |
"name": "CEO", | |
"parent": null, | |
"id": "5847e80312896b2fa49ce428" | |
}, { | |
"name": "A", | |
"parent": "5847e80312896b2fa49ce428", | |
"id": "5847f58289046550aa05a49d" | |
}, { | |
"name": "A1", | |
"parent": "5847f58289046550aa05a49d", | |
"id": "584804b073697edd3d372529" | |
}, { | |
"name": "A2", | |
"parent": "5847e80312896b2fa49ce428", | |
"id": "584804b073697edd3d372539" | |
}] | |
const rec = (parent, arr) => { | |
const ref = parent ? parent.id : null | |
const children = arr.reduce((ac, x) => { | |
if (x.parent === ref) | |
ac.push(rec(x, arr)) | |
return ac | |
}, []) | |
if (parent) | |
parent.children = children | |
return ( | |
parent ? | |
parent : | |
children[0] | |
) | |
} | |
const res = rec(null, d) | |
console.log(res) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment