Skip to content

Instantly share code, notes, and snippets.

@ggondim
Created January 18, 2022 00:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ggondim/35376795cb832103e466fc158db74af4 to your computer and use it in GitHub Desktop.
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)
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;
}
@alexrififi
Copy link

Big thanks! ❤️

@archidigital
Copy link

Many thanks!

@danishiqbal4
Copy link

danishiqbal4 commented Apr 9, 2022

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