In JavaScript, converting normal array data into tree-structured data is a common task, especially when processing hierarchical data (such as classification, organizational structure, etc.). Here is a detailed step description showing how to convert a flat array into a tree data structure.
Sample data
Suppose we have the following flat array, each element represents a node, and each node contains oneid
And oneparentId
,parentId
Used to represent the relationship of the parent node:
const data = [ { id: 1, name: 'Root', parentId: null }, { id: 2, name: 'Child 1', parentId: 1 }, { id: 3, name: 'Child 2', parentId: 1 }, { id: 4, name: 'Grandchild 1', parentId: 2 }, { id: 5, name: 'Grandchild 2', parentId: 2 }, ];
Target
Convert the above data into the following tree structure:
[ { id: 1, name: 'Root', children: [ { id: 2, name: 'Child 1', children: [ { id: 4, name: 'Grandchild 1', children: [] }, { id: 5, name: 'Grandchild 2', children: [] } ] }, { id: 3, name: 'Child 2', children: [] } ] } ]
Implementation steps
Create an empty object to store references to each node:
const nodeMap = {};
Iterate through the array, initialize the node and fill itnodeMap
:
(item => { nodeMap[] = { ...item, children: [] }; });
This way every node is mapped tonodeMap
and each node has onechildren
Attributes are used to store child nodes.
Iterate through the array and add each node to its parent node'schildren
middle:
(item => { if () { // If the node has a parent node, add it to the parent node's children const parent = nodeMap[]; if (parent) { (nodeMap[]); } } });
Extract the root node:
The root node isparentId
fornull
node. We cannodeMap
Find these nodes in
const tree = (nodeMap).filter(node => === null);
Complete code example
Here is the complete code that brings the above steps together:
const data = [ { id: 1, name: 'Root', parentId: null }, { id: 2, name: 'Child 1', parentId: 1 }, { id: 3, name: 'Child 2', parentId: 1 }, { id: 4, name: 'Grandchild 1', parentId: 2 }, { id: 5, name: 'Grandchild 2', parentId: 2 }, ]; function buildTree(data) { const nodeMap = {}; // Initialize nodeMap (item => { nodeMap[] = { ...item, children: [] }; }); // Build a tree structure (item => { if () { const parent = nodeMap[]; if (parent) { (nodeMap[]); } } }); // Extract the root node return (nodeMap).filter(node => === null); } const tree = buildTree(data); ((tree, null, 2));
explain
Initialize node mapping:
nodeMap
Used to store references to each node and initialize each node'schildren
is an empty array.
Establish a father-son relationship:
Iterate through the data, find the parent node of each node, and add the current node to the parent node'schildren
middle.
Extract the root node:
By filteringnodeMap
middleparentId
fornull
The node of the tree is obtained.
Recursive function implementation
function buildTree(flatData, parentId = null) { return flatData .filter(node => === parentId) .map(node => ({ ...node, children: buildTree(flatData, ) })); }
Parameter description
-
flatData
: Flat array data. Each element containsid
andparentId
, used to represent nodes and their parent node relationship. -
parentId
: The ID of the parent node to be processed. Default isnull
, represents the root node at the initial call.
Function implementation details
Filter nodes:
(node => === parentId)
-
filter
The method will returnflatData
All inparentId
Equal to currentparentId
node. This means we are looking for all direct children. - On the first call,
parentId
yesnull
, so what we get is all the root nodes.
Mapping nodes:
.map(node => ({ ...node, children: buildTree(flatData, ) }))
-
map
The method executes a callback function on each filtered node. - The purpose of the callback function is to convert the current node
children
Set the property to a recursive callbuildTree
The result of the function.
Recursive call:
buildTree(flatData, )
- For each node, we call again
buildTree
function to the current nodeid
As newparentId
。 - This will find all the children of the current node and will use these children as the current node's
children
property.
Recursive process
Initial call:
buildTree(flatData)
On the first callparentId
yesnull
, which means we look up all root nodes.
Find child nodes:
For each root node,buildTree
Will be called to find the direct child node of the node.
Recursion step by step:
For each child node,buildTree
It will call itself recursively and continue to search for the child nodes of the child node until all nodeschildren
The properties are filled.
Example
Suppose we have the following flat data:
const data = [ { id: 1, name: 'Root', parentId: null }, { id: 2, name: 'Child 1', parentId: 1 }, { id: 3, name: 'Child 2', parentId: 1 }, { id: 4, name: 'Grandchild 1', parentId: 2 }, { id: 5, name: 'Grandchild 2', parentId: 2 } ];
CallbuildTree(data)
hour:
The first floor:
parentId
yesnull
, find the ID as1
root node.
The second floor:
For the root node (ID is1
), callbuildTree(data, 1)
Find its child node and find the ID2
and3
node.
The third floor:
For ID is2
node, callbuildTree(data, 2)
Find its child node and find the ID4
and5
node.
The fourth floor:
ID is4
and5
The node has no child nodes, so it terminates recursively and returns emptychildren
Array.
The final tree data structure is as follows:
[ { id: 1, name: 'Root', children: [ { id: 2, name: 'Child 1', children: [ { id: 4, name: 'Grandchild 1', children: [] }, { id: 5, name: 'Grandchild 2', children: [] } ] }, { id: 3, name: 'Child 2', children: [] } ] } ]
Summarize
thisbuildTree
Functions use recursive methods to build tree-shaped data structures. Through filtering, mapping, and recursive calls, it builds the child nodes of each node layer by layer until all nodeschildren
The properties are all filled correctly. This method is simple and efficient, suitable for processing hierarchical data.
This is the article about JavaScript that implements the transformation of ordinary array data into tree data structures. For more related contents of JS ordinary array conversion of tree structures, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!