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 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 Approach
  • Iterative Approach

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.

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 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.

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