Open In App

Build Tree Array from JSON in JavaScript

Last Updated : 08 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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] ] }
]

Next Article

Similar Reads