How to Recursively Build a JSON Tree Structure in JavaScript ?
Last Updated :
18 Mar, 2024
To create a JSON tree structure recursively in JavaScript we need to create a recursive function that traverses the data and constructs the tree. We can create a JSON tree structure recursively in JavaScript using the below methods.
Using Arrays to build a JSON tree structure
In this method, we use JavaScript arrays to represent nodes in the tree structure. Arrays recursively build the tree by iterating over the data array and creating nodes for each item. If an item has children, it recursively calls the buildTree
function to construct the children nodes.
Example: The below code recursively builds a JSON tree structure using JavaScript arrays.
JavaScript
function buildTree(data, parentId = null) {
let tree = [];
data.forEach(item => {
// Check if the item belongs to the current parent
if (item.parentId === parentId) {
// Recursively build the children of the current item
let children = buildTree(data, item.id);
// If children exist, assign them to the current item
if (children.length) {
item.children = children;
}
// Add the current item to the tree
tree.push(item);
}
});
return tree;
}
const data = [
{ id: 1, parentId: null, name: "Root" },
{ id: 2, parentId: 1, name: "Folder A" },
{ id: 3, parentId: 1, name: "Folder B" },
{ id: 4, parentId: 2, name: "File 1" },
{ id: 5, parentId: 2, name: "File 2" },
{ id: 6, parentId: 3, name: "File 3" }
];
const tree = buildTree(data);
console.log(JSON.stringify(tree, null, 2));
Output:
[
{
"id": 1,
"parentId": null,
"name": "Root",
"children": [
{
"id": 2,
"parentId": 1,
"name": "Folder A",
"children": [
{
"id": 4,
"parentId": 2,
"name": "File 1"
},
{
"id": 5,
"parentId": 2,
"name": "File 2"
}
]
},
{
"id": 3,
"parentId": 1,
"name": "Folder B",
"children": [
{
"id": 6,
"parentId": 3,
"name": "File 3"
}
]
}
]
}
]
Using a Class to build a JSON tree structure
In this method, we define a Node
class to represent each node in the tree structure. It recursively builds the tree by creating instances of the Node
class for each item in the data array. If an item has children, it recursively calls the buildTree
function to construct the children nodes.
Example : The below code recursively builds a JSON tree structure using JavaScript classes.
JavaScript
class Node {
constructor(id, parentId, name) {
this.id = id;
this.parentId = parentId;
this.name = name;
this.children = [];
}
}
function buildTree(data, parentId = null) {
const nodes = {};
// Create nodes for each item in the data
data.forEach(({ id, parentId, name }) => {
nodes[id] = new Node(id, parentId, name);
});
const tree = [];
Object.values(nodes).forEach(node => {
// Check if the node belongs to the current parent
if (node.parentId === parentId) {
// Recursively build the children of the current node
const children = buildTree(data, node.id);
// Set the children of the current node
node.children = children;
// Add the current node to the tree
tree.push(node);
}
});
return tree;
}
const data = [
{ id: 1, parentId: null, name: "Root" },
{ id: 2, parentId: 1, name: "Section A" },
{ id: 3, parentId: 1, name: "Section B" },
{ id: 4, parentId: 2, name: "Page 1" },
{ id: 5, parentId: 2, name: "Page 2" },
{ id: 6, parentId: 3, name: "Page 3" }
];
const tree = buildTree(data);
console.log(JSON.stringify(tree, null, 2));
Output:
[
{
"id": 1,
"parentId": null,
"name": "Root",
"children": [
{
"id": 2,
"parentId": 1,
"name": "Section A",
"children": [
{
"id": 4,
"parentId": 2,
"name": "Page 1",
"children": []
},
{
"id": 5,
"parentId": 2,
"name": "Page 2",
"children": []
}
]
},
{
"id": 3,
"parentId": 1,
"name": "Section B",
"children": [
{
"id": 6,
"parentId": 3,
"name": "Page 3",
"children": []
}
]
}
]
}
]
Similar Reads
How to view array of a structure in JavaScript ?
The Javascript arrays are heterogeneous. The structure of the array is the same which is enclosed between two square brackets [ ], and the string should be enclosed between either "double quotes" or 'single quotes'. You can get the structure of by using JSON.stringify() or not, here you will see the
3 min read
How to print a circular structure in a JSON like format using JavaScript ?
The circular structure is when you try to reference an object which directly or indirectly references itself. Example: A -> B -> A OR A -> A Circular structures are pretty common while developing an application. For Example, suppose you are developing a social media application where each u
4 min read
Build Tree Array from JSON in JavaScript
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
3 min read
How to Recursively Map Object in JavaScript ?
Recursively mapping objects in JavaScript involves traversing through nested objects and applying a function to each key-value pair. This process allows for transforming the structure of an object according to a specific logic or requirement. Below are the approaches to recursively map an object in
3 min read
How to Regroup JSON array in JavaScript
Regrouping JSON arrays in JavaScript is crucial for organizing data efficiently, simplifying data management tasks, and ensuring better data integration across systems. Here, we will regroup JSON arrays in JavaScript in two methods to achieve this using the reduce method and an iterative approach. T
3 min read
How to Serialize JSON in JavaScript ?
JSON (JavaScript Object Notation) serialization is a fundamental concept in JavaScript, allowing the conversion of JavaScript objects into strings that can be easily transmitted over a network or stored in a file. We will explore how to serialize JSON in JavaScript using JSON.stringify(). Approach I
1 min read
How to Pretty Print JSON String in JavaScript?
To pretty print JSON, you can format JSON strings with proper indentation, making them easy to read and debug. In JavaScript, you can achieve this using JSON.stringify() with optional parameters to specify the indentation level.Pretty printing JSON adds line breaks and spaces for readability.It is c
3 min read
How to Parse JSON in JavaScript ?
Parse JSON in JavaScript, accepting a JSON string as input and returning a corresponding JavaScript object with two methods, using JSON.parse() for parsing JSON strings directly and employing the fetch API to parse JSON responses from web APIs. These techniques are crucial for seamless data manipula
2 min read
How to Convert a Map to JSON String in JavaScript ?
A Map is a collection of key-value pairs, where each key is unique. In this article, we will see how to convert a Map to a JSON (JavaScript Object Notation) string in JavaScript. However, JSON.stringify() does not directly support Map objects. Table of ContentUsing Object.fromEntries() MethodUsing A
2 min read
How to Add Backslash in JSON String JavaScript ?
In JavaScript, adding a backslash to a JSON string is important to properly escape special characters, ensuring the integrity and correctness of the JSON format for data processing and storage. Table of Content Using JSON.parse() and JSON.stringify()Using for LoopUsing Array.prototype.map() and Stri
2 min read