Introduction
This article is going to talk about how to make tree view from flat array.
typescript
const arr = [
{ id: 1, parentId: 0, name: 'test 1' },
{ id: 2, parentId: 1, name: 'test 2' },
{ id: 3, parentId: 1, name: 'test 3' },
{ id: 4, parentId: 0, name: 'test 4' },
{ id: 5, parentId: 3, name: 'test 5' },
{ id: 6, parentId: 3, name: 'test 6' },
]
Let's consider that there are above array.
To generate tree, array must have key and parent key.
The id
property is key and parentId
is parent key in the example array.
Function
typescript
const genTree = (array, parentId) =>
array.filter(element => element.parentId === parentId)
.map(element => ({ ...element, children: genTree(array, element.id)}));
Recursive is most a easiest way to make tree.
Generated children will be in the childeren
property.
Output
json
[
{
"id": 1,
"parentId": 0,
"name": "test 1",
"children": [
{
"id": 2,
"parentId": 1,
"name": "test 2",
"children": []
},
{
"id": 3,
"parentId": 1,
"name": "test 3",
"children": [
{
"id": 5,
"parentId": 3,
"name": "test 5",
"children": []
},
{
"id": 6,
"parentId": 3,
"name": "test 6",
"children": []
}
]
}
]
},
{
"id": 4,
"parentId": 0,
"name": "test 4",
"children": []
}
]