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: Table of Content Recursive ApproachIterative ApproachRecursive ApproachThis 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. JavaScript function GFG(jsonObj) { let treeArray = []; function traverse(node) { let treeNode = { id: node.id, name: node.name, children: [] }; if (node.children && node.children.length > 0) { node .children .forEach(child => { treeNode .children .push(traverse(child)); }); } return treeNode; } if (jsonObj && jsonObj.length > 0) { jsonObj .forEach(rootNode => { treeArray .push(traverse(rootNode)); }); } return treeArray; } const json = [ { id: 1, name: "Root", children: [{ id: 2, name: "Child 1", children: [] }] }, { id: 3, name: "Another Root", children: [{ id: 4, name: "Child 2", children: [] }] } ]; const tree = GFG(json); console.log(tree); Output : [ { id: 1, name: 'Root', children: [ [Object] ] }, { id: 3, name: 'Another Root', children: [ [Object] ] }]Iterative ApproachThis 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. JavaScript function GFG(jsonObj) { let treeArray = []; let stack = []; // Initialize stack with root nodes for (let i = 0; i < jsonObj.length; i++) { stack .push({ node: jsonObj[i], parentIndex: -1 }); } while (stack.length > 0) { let { node, parentIndex } = stack .pop(); let treeNode = { id: node.id, name: node.name, children: [] }; if (parentIndex !== -1) { treeArray[parentIndex] .children .push(treeNode); } else { treeArray .push(treeNode); } // Add children nodes to the stack if (node.children && node.children.length > 0) { for (let i = node .children .length - 1; i >= 0; i--) { stack .push({ node: node.children[i], parentIndex: treeArray.length - 1 }); } } } return treeArray; } const json = [ { id: 1, name: "Root", children: [{ id: 2, name: "Child 1", children: [] }] }, { id: 3, name: "Another Root", children: [{ id: 4, name: "Child 2", children: [] }] } ]; // Build tree using the iterative approach const tree = GFG(json); console.log(tree); Output: [ { id: 3, name: 'Another Root', children: [ [Object] ] }, { id: 1, name: 'Root', children: [ [Object] ] }] Comment More infoAdvertise with us Next Article Build Tree Array from JSON in JavaScript S subramanyasmgm Follow Improve Article Tags : JavaScript Web Technologies JSON Similar Reads Build Tree Array from Flat Array in JavaScript To convert a flat array of comments into a tree-like structure using JavaScript. This technique is particularly useful when you need to render nested comments or any other hierarchical data in your web application. We will write a function called buildCommentsTree that takes the flat array of commen 7 min read How to Remove Duplicates in JSON Array JavaScript ? In JavaScript, removing duplicates from a JSON array is important for data consistency and efficient processing. We will explore three different approaches to remove duplicates in JSON array JavaScript. Use the methods below to remove Duplicates in JSON Array JavaScript. Table of Content Using SetUs 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 Formatting Dynamic JSON array JavaScript Formatting a Dynamic JSON array is important because it organizes complex data structures, making them easier to read, manipulate, and communicate within applications and APIs. We will explore approaches to formatting dynamic JSON arrays in JavaScript. Below are the approaches to format dynamic JSON 2 min read Convert an Array to JSON in JavaScript Given a JavaScript Array and the task is to convert an array to JSON Object. Below are the approaches to convert an array to JSON using JsvaScript: Table of ContentJSON.stringify() methodObject.assign() methodJSON.stringify() methodThe use of JSON is to exchange data to/from a web server. While send 2 min read How to Convert JSON to ArrayBuffer in JavaScript? An ArrayBuffer is a complex data type, and structures which has a fixed length and takes binary content as the whole. Any variable that contains pure binary data will be defined in JavaScript as Simple Data, however on some occasions it is sometimes necessary to convert JSON data to an ArrayBuffer, 4 min read Types of Arrays in JavaScript A JavaScript array is a collection of multiple values at different memory blocks but with the same name. The values stored in an array can be accessed by specifying the indexes inside the square brackets starting from 0 and going to the array length - 1([0]...[n-1]). A JavaScript array can be classi 3 min read Set to Array in JS or JavaScript This article will show you how to convert a Set to an Array in JavaScript. A set can be converted to an array in JavaScript in the following ways:1. Using Spread OperatorThe JavaScript Spread Operator can be used to destructure the elements of the array and then assign them to a new variable in the 2 min read Convert Array to String in JavaScript In JavaScript, converting an array to a string involves combining its elements into a single text output, often separated by a specified delimiter. This is useful for displaying array contents in a readable format or when storing data as a single string. The process can be customized to use differen 7 min read JavaScript | JSON Arrays The JSON Arrays is similar to JavaScript Arrays. Syntax of Arrays in JSON Objects: // JSON Arrays Syntax { "name":"Peter parker", "heroName": "Spiderman", "friends" : ["Deadpool", "Hulk", "Wolverine"] } Accessing Array Values: The Array values can be accessed using the index of each element in an Ar 2 min read Like