Building Tree Structures from Flat Array Data in JavaScript
When working with complex hierarchical data, it becomes necessary to organize it into a tree-like structure for analysis and presentation. In this case, an ordered JSON file contains the data with each entry having an id, parentId, level, and text. The task is to convert this flat data structure into a nested hierarchy.
To achieve this transformation efficiently, it is important to leverage a map-lookup strategy. This involves creating a map that maps each id to its index in the list. By utilizing this map, the nested hierarchy can be constructed in one pass, eliminating the need for multiple loops.
The following JavaScript function demonstrates the map-lookup approach to building a tree structure:
function list_to_tree(list) { var map = {}, node, roots = [], i; for (i = 0; i < list.length; i += 1) { map[list[i].id] = i; // initialize the map list[i].children = []; // initialize the children } for (i = 0; i < list.length; i += 1) { node = list[i]; if (node.parentId !== "0") { // if you have dangling branches check that map[node.parentId] exists list[map[node.parentId]].children.push(node); } else { roots.push(node); } } return roots; }
By creating a map to quickly access parents and initializing child lists for each node, the function can efficiently merge both for-loops. This approach supports multiple roots and can handle dangling branches or ignore them with a simple modification.
To demonstrate the function's functionality, you can execute it with the following input:
var 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 } ]; console.log(list_to_tree(entries));
This will output the hierarchical tree structure with the expected relationships between the nodes. By leveraging the map-lookup strategy, this approach offers an efficient and flexible solution for transforming flat hierarchical data into well-structured tree arrays.
The above is the detailed content of How Can I Efficiently Convert a Flat Array of Hierarchical Data into a Nested Tree Structure in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!