VOOZH about

URL: https://www.geeksforgeeks.org/javascript/build-tree-array-from-json-in-javascript/

⇱ Build Tree Array from JSON in JavaScript - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Build Tree Array from JSON in JavaScript

Last Updated : 5 Aug, 2025

Building a tree array from JSON in JavaScript involves converting a JSON object representing a hierarchical structure into an array that reflects the parent-child relationships. This tree array can be useful for various purposes like rendering hierarchical data in UI components performing tree-based operations, or processing data in a structured manner.

Below are the approaches to build a tree array from JSON in JavaScript:

Recursive Approach

This approach recursively traverses the JSON object identifying parent-child relationships and builds the tree array accordingly.

Syntax:

function buildTreeRecursive(jsonObj) {
// Recursive function implementation
}

Example: To demonstrate creating a tree array from JSON in JavaScript using recursion.

Output :

[
{ id: 1, name: 'Root', children: [ [Object] ] },
{ id: 3, name: 'Another Root', children: [ [Object] ] }
]

Iterative Approach

This approach iterates over the JSON object using the stack or queue data structure maintaining parent-child relationships and constructs the tree array iteratively.

Syntax:

function buildTreeIterative(jsonObj) {
// Iterative function implementation
}

Example: To demonstrate creating tree array from JSON in JavaScript using iterative approach.

Output:

[
{ id: 3, name: 'Another Root', children: [ [Object] ] },
{ id: 1, name: 'Root', children: [ [Object] ] }
]
Comment
Article Tags: