Building Hierarchical Tree Data Structure from Flat JSON Array in JavaScript
In scenarios involving complex JSON data, it becomes essential to organize it hierarchically, especially for representing tree-like structures. This article addresses how to transform a flat JSON array into a hierarchical tree in JavaScript.
Problem
Given a flat JSON array consisting of objects with three key properties:
The task is to convert this flat array into a hierarchical tree structure, where each parent node encapsulates its child nodes.
Solution
An efficient approach utilizes a map-lookup algorithm to build the tree. The algorithm iterates through the flat array twice:
Implementation
The following JavaScript code snippet showcases the implementation of the tree-building algorithm:
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") { // handle dangling branches here list[map[node.parentId]].children.push(node); } else { roots.push(node); } } return roots; }
Usage
To convert a flat JSON array into a hierarchical tree structure:
var entries = [ // ... entries as in the provided example ]; var tree = list_to_tree(entries); // The resulting `tree` is the hierarchical data structure
Conclusion
The algorithm presented in this article effectively converts flat JSON arrays into hierarchical tree structures in JavaScript. It relies on a map-lookup approach for efficient construction, making it suitable for handling complex data sets.
The above is the detailed content of How to Efficiently Transform a Flat JSON Array into a Hierarchical Tree Structure in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!