Created
May 3, 2023 12:44
-
-
Save maradondt/3c332cc5cd7098be16bf92613072ea3d to your computer and use it in GitHub Desktop.
create a tree from list
This file contains hidden or 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 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