json to nary tree with tree constructor in javascript

Here's an example code that uses recursion to convert a JSON object to a n-ary tree:

index.tsx
class TreeNode {
  constructor(name) {
    this.name = name;
    this.children = [];
  }
}

function jsonToTree(json) {
  const root = new TreeNode(json.name);
  if (json.children) {
    for (const child of json.children) {
      root.children.push(jsonToTree(child));
    }
  }
  return root;
}
296 chars
17 lines

In this code, we define a TreeNode class to represent nodes in the n-ary tree. Each TreeNode has a name and an array of children, which are also TreeNode objects.

The jsonToTree function takes a JSON object as input and recursively converts it to a TreeNode object. We first create a TreeNode object for the root node, and then iterate over the children array of the JSON object. For each child, we recursively call jsonToTree to create a TreeNode object and add it as a child of the root. Finally, we return the root node.

Here's an example usage of the jsonToTree function:

index.tsx
const json = {
  name: 'root',
  children: [
    {
      name: 'child1'
    },
    {
      name: 'child2',
      children: [
        {
          name: 'grandchild1'
        },
        {
          name: 'grandchild2'
        }
      ]
    }
  ]
};

const root = jsonToTree(json);

console.log(root.name); // Output: 'root'
console.log(root.children.length); // Output: 2
console.log(root.children[1].children.length); // Output: 2
430 chars
26 lines

gistlibby LogSnag