Created
January 18, 2022 00:03
-
-
Save ggondim/35376795cb832103e466fc158db74af4 to your computer and use it in GitHub Desktop.
Build a object tree (parent/children) given an object array of type T, the object ID key (elementKey) and the object parent key (parentKey)
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
type TreeItem<T> = T & { children: TreeItem<T>[] }; | |
export default function buildTree<T>(array: T[], elementKey: keyof T, parentKey: keyof T): TreeItem<T>[] { | |
let tree = [] as TreeItem<T>[]; | |
for (let i = 0; i < array.length; i++) { | |
if (array[i][parentKey]) { | |
let parent = array.filter(elem => elem[elementKey] === array[i][parentKey]).pop() as TreeItem<T>; | |
if (!parent['children']) { | |
parent.children = []; | |
} | |
parent.children.push(array[i] as TreeItem<T>) | |
} else { | |
tree.push(array[i] as TreeItem<T>); | |
} | |
} | |
return tree; | |
} |
Many thanks!
Can we modify it so that we can pass a param for how many levels we want starting from a specific ID?
Suppose our dataset can go upto 10 levels but we want to build a tree of only 3 levels starting from an ID that is on level 5.
e.g: We want 3 levels from a specific ID that is on level 5 so that our final tree will only have level 5 (specific ID), 6, 7 and 8
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Big thanks! ❤️