Skip to content

Instantly share code, notes, and snippets.

@maradondt
Created May 3, 2023 12:44
Show Gist options
  • Save maradondt/3c332cc5cd7098be16bf92613072ea3d to your computer and use it in GitHub Desktop.
Save maradondt/3c332cc5cd7098be16bf92613072ea3d to your computer and use it in GitHub Desktop.
create a tree from list
type BaseObj = {
id: string;
parentId: string | null;
};
type Result<T extends BaseObj> = T & {
children: Result<T>[];
};
export const listToTree = (
arr: BaseObj[],
parentId: string | null = null,
resolveId = ({ id }: BaseObj) => id,
resolveParent = ({ parentId }: BaseObj) => parentId
) => {
const out: Result<BaseObj>[] = [];
for (const i in arr) {
if (resolveParent(arr[i]) === parentId) {
const children = listToTree(arr, resolveId(arr[i]));
const { id, parentId, ...omit } = arr[i];
const res: Result<BaseObj> = {
id,
parentId,
children: [],
};
res.children = children || [];
out.push(res);
}
}
return out;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment