hope you doing well. I have a question about how to clean up an array and make it a new one. I give you context, I have the following array:
const array = [
{ id: 1, parentId: null, name: Example },
{ id: 2, parentId: 1, name: Example },
{ id: 3, parentId: 1, name: Example },
{ id: 4, parentId: 1, name: Example },
{ id: 5, parentId: 2, name: Example },
{ id: 6, parentId: 2, name: Example },
{ id: 7, parentId: 6, name: Example },
{ id: 8, parentId: 7, name: Example },
{ id: 9, parentId: 7, name: Example },
];
I would like to know how I can convert it into an array structured in such a way that the first elements are the ones that are connected to the smallest parentId, in this case 1. And later, according to this value, new arrays are formed within its object. For example:
const array = [
{ id: 1, parentId: null, name: Example },
{ id: 2, parentId: 1, name: Example },
{ id: 3, parentId: 1, name: Example },
{ id: 4, parentId: 1, name: Example },
{ id: 5, parentId: 2, name: Example },
{ id: 6, parentId: 2, name: Example },
{ id: 7, parentId: 6, name: Example },
{ id: 8, parentId: 7, name: Example },
{ id: 9, parentId: 7, name: Example },
];
Into this:
const array = [
{
id: 1,
parentId: null,
name: Example,
options: [
{
id: 2,
parentId: 1,
name: Example,
options: [
{ id: 5, parentId: 2, name: Example },
{ id: 6, parentId: 2, name: Example },
]
},
{ id: 3, parentId: 1, name: Example },
{ id: 4, parentId: 1, name: Example },
{
id: 7,
parentId: 1,
name: Example,
options: [
{ id: 8, parentId: 7, name: Example },
{ id: 9, parentId: 7, name: Example },
]
},
]
},
];
The array now sorts its options based on the parent id. Could anyone help me? I really find myself confused.
I tried using the map method, but its getting hard after some elements.
3
Answers
It can help you. 🙂
You can use a recursive function for this. The function assumes that the top-level items have
parentId
of null. If this is not the case, you may need to modify the function to pass in the top-levelparentId
value as an argument.I added comments in the snippets to explain what it does exactly.