Skip to content

Instantly share code, notes, and snippets.

@DykiSA
Last active April 20, 2018 07:08
Show Gist options
  • Save DykiSA/160b4d8b280ac49a251d0db31472df8f to your computer and use it in GitHub Desktop.
Save DykiSA/160b4d8b280ac49a251d0db31472df8f to your computer and use it in GitHub Desktop.
Create recrursive tree from relational data source
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