SoFunction
Updated on 2025-04-07

JavaScript: Steps for converting ordinary array data into tree data structures

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 oneidAnd oneparentIdparentIdUsed 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 tonodeMapand each node has onechildrenAttributes are used to store child nodes.

Iterate through the array and add each node to its parent node'schildrenmiddle:

(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 isparentIdfornullnode. We cannodeMapFind 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

nodeMapUsed to store references to each node and initialize each node'schildrenis 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'schildrenmiddle.

Extract the root node

By filteringnodeMapmiddleparentIdfornullThe 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 containsidandparentId, 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)
  • filterThe method will returnflatDataAll inparentIdEqual to currentparentIdnode. This means we are looking for all direct children.
  • On the first call,parentIdyesnull, so what we get is all the root nodes.

Mapping nodes

.map(node => ({
  ...node,
  children: buildTree(flatData, )
}))
  • mapThe method executes a callback function on each filtered node.
  • The purpose of the callback function is to convert the current nodechildrenSet the property to a recursive callbuildTreeThe result of the function.

Recursive call

buildTree(flatData, )
  • For each node, we call againbuildTreefunction to the current nodeidAs newparentId
  • This will find all the children of the current node and will use these children as the current node'schildrenproperty.

Recursive process

Initial call

buildTree(flatData)

On the first callparentIdyesnull, which means we look up all root nodes.

Find child nodes

For each root node,buildTreeWill be called to find the direct child node of the node.

Recursion step by step

For each child node,buildTreeIt will call itself recursively and continue to search for the child nodes of the child node until all nodeschildrenThe 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

parentIdyesnull, find the ID as1root node.

The second floor

For the root node (ID is1), callbuildTree(data, 1)Find its child node and find the ID2and3node.

The third floor

For ID is2node, callbuildTree(data, 2)Find its child node and find the ID4and5node.

The fourth floor

ID is4and5The node has no child nodes, so it terminates recursively and returns emptychildrenArray.

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

thisbuildTreeFunctions 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 nodeschildrenThe 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!