Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Take in array of objects and convert the above JSON to a Tree-structure in JavaScript
In web development, you often need to convert flat arrays of hierarchical data into tree structures. This is common when working with organizational charts, file systems, or nested menus.
Input Data Structure
Suppose we have an array of objects representing parent-child relationships:
const arr = [
{
"parentIndex": '0',
"childIndex": '3',
"parent": "ROOT",
"child": "root3"
},
{
"parentIndex": '3',
"childIndex": '2',
"parent": "root3",
"child": "root2"
},
{
"parentIndex": '3',
"childIndex": '1',
"parent": "root3",
"child": "root1"
}
];
Expected Tree Structure
We want to transform this into a hierarchical tree structure:
{
text: { name: "root3" },
children: [
{
text: { name: "root2" }
},
{
text: { name: "root1" }
}
]
}
Solution Using Recursion
Here's a complete solution that uses recursive functions to build the tree:
const arr = [
{
"parentIndex": '0',
"childIndex": '3',
"parent": "ROOT",
"child": "root3"
},
{
"parentIndex": '3',
"childIndex": '2',
"parent": "root3",
"child": "root2"
},
{
"parentIndex": '3',
"childIndex": '1',
"parent": "root3",
"child": "root1"
}
];
// Helper function to filter array based on condition
const partial = (arr = [], condition) => {
const result = [];
for (let i = 0; i {
let subItems = partial(items, n => n.parent === parentKey);
const result = [];
for (let i = 0; i
[
{
"text": {
"name": "root3"
},
"children": [
{
"text": {
"name": "root2"
}
},
{
"text": {
"name": "root1"
}
}
]
}
]
How It Works
The solution works in two main steps:
-
Filter function: The
partial function filters the array to find all items with a specific parent.
-
Recursive builder: The
findNodes function recursively builds each node by finding its children and calling itself again.
Key Points
- The algorithm starts with a root parent key (like 'ROOT')
- For each parent, it finds all direct children
- For each child, it recursively searches for grandchildren
- The recursion stops when no more children are found
Conclusion
This recursive approach efficiently converts flat hierarchical data into tree structures. The pattern is useful for building navigation menus, organizational charts, and any nested data visualization.
Advertisements
