Last active
July 20, 2020 15:30
-
-
Save rrmhearts/e355c4f3340b7d6f976c2724f16a1799 to your computer and use it in GitHub Desktop.
Create Tree Structure from list of nodes with parent property
This file contains 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
const idMapping = data.reduce((acc, el, i) => { | |
acc[el.id] = i; | |
return acc; | |
}, {}); | |
let root = []; | |
data.forEach(el => { | |
// Handle the root element | |
if (el.parent === null) { | |
root.push(el); | |
return; | |
} | |
// Use our mapping to locate the parent element in our data array | |
const parentEl = data[idMapping[el.parent]]; | |
// Add our current el to its parent's `nodes` array | |
if (parentEl && parentEl.hasOwnProperty('parent')) | |
parentEl.nodes = [...(parentEl.nodes || []), el]; | |
}); | |
// Source: https://typeofnan.dev/an-easy-way-to-build-a-tree-with-object-references/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment