Introduction
In JavaScript, working with hierarchical data is essential for various applications, such as creating tree structures or navigation menus. When data is stored in a flat array, it becomes necessary to transform it into a hierarchical structure to facilitate data manipulation and visualization. This article will demonstrate an effective method to build a tree array from a flat array in JavaScript.
Problem
Given a complex JSON file consisting of objects with the following properties:
The task is to convert the flat JSON structure into a hierarchical tree structure with nested objects representing the parent-child relationships.
Solution
The solution leverages a map-lookup approach to efficiently construct the hierarchical tree structure. The algorithm involves two steps:
Create a Map to Index Objects:
Build the Tree Structure:
Iterate through the flat array again:
Example
Consider the following flat JSON array:
const entries = [{ "id": "12", "parentId": "0", "text": "Man", "level": "1", "children": null }, { "id": "6", "parentId": "12", "text": "Boy", "level": "2", "children": null }, { "id": "7", "parentId": "12", "text": "Other", "level": "2", "children": null }, { "id": "9", "parentId": "0", "text": "Woman", "level": "1", "children": null }, { "id": "11", "parentId": "9", "text": "Girl", "level": "2", "children": null }];
Applying the above algorithm to this flat array will output the following hierarchical tree structure:
const result = [ { "id": "12", "parentId": "0", "text": "Man", "level": "1", "children": [ { "id": "6", "parentId": "12", "text": "Boy", "level": "2", "children": null }, { "id": "7", "parentId": "12", "text": "Other", "level": "2", "children": null } ] }, { "id": "9", "parentId": "0", "text": "Woman", "level": "1", "children": { "id": "11", "parentId": "9", "text": "Girl", "level": "2", "children": null } } ];
Conclusion
The presented algorithm provides an efficient way to convert a flat array of hierarchical data into a structured tree array in JavaScript. This approach leverages a map-lookup to optimize the process and supports multiple root nodes. It's ideal for situations where you need to create tree structures from complex data for further manipulation or visualization.
The above is the detailed content of How to Efficiently Build a Hierarchical Tree Structure from a Flat Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!