Skip to content

Instantly share code, notes, and snippets.

@otonielguajardo
Created October 13, 2021 00:09
Show Gist options
  • Save otonielguajardo/d3435bfe0bc576173d07bf013480217f to your computer and use it in GitHub Desktop.
Save otonielguajardo/d3435bfe0bc576173d07bf013480217f to your computer and use it in GitHub Desktop.
Create a nested array of objects with id and parentId pointers
export const formatNested = function (flatArray: any[], id: any, parentId: any): Array<any> {
const collection: Array<any> = [];
flatArray.forEach((item) => (collection[item[id]] = { ...item, children: [] }));
const result: Array<any> = [];
flatArray.forEach((item) => {
if (item[parentId]) {
if (collection[item[parentId]]) {
collection[item[parentId]].children.push(collection[item[id]]);
}
} else {
result.push(collection[item[id]]);
}
});
return result;
};
// formatNested(collection, 'id', 'parent');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment