Created
October 13, 2021 00:09
-
-
Save otonielguajardo/d3435bfe0bc576173d07bf013480217f to your computer and use it in GitHub Desktop.
Create a nested array of objects with id and parentId pointers
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
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