Skip to content

Instantly share code, notes, and snippets.

@rrmhearts
Last active July 20, 2020 15:30
Show Gist options
  • Save rrmhearts/e355c4f3340b7d6f976c2724f16a1799 to your computer and use it in GitHub Desktop.
Save rrmhearts/e355c4f3340b7d6f976c2724f16a1799 to your computer and use it in GitHub Desktop.
Create Tree Structure from list of nodes with parent property
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