json to nary tree in javascript

Here's a function that takes a JSON object and converts it to a n-ary tree data structure:

index.tsx
function jsonToNaryTree(json) {
  // create root node
  const root = {
    value: null,
    children: []
  };

  // recursively add nodes to the tree
  function traverse(obj, parent) {
    const node = { value: obj.name, children: [] };
    parent.children.push(node);

    if (obj.children) {
      obj.children.forEach(child => {
        traverse(child, node);
      });
    }
  }

  traverse(json, root);
  return root.children;
}
434 chars
23 lines

Assuming you have a JSON object like this:

index.tsx
const json = {
  name: "root",
  children: [
    {
      name: "node1",
      children: [
        {
          name: "node2"
        },
        {
          name: "node3"
        }
      ]
    },
    {
      name: "node4"
    }
  ]
};
233 chars
20 lines

You can convert it to a n-ary tree like this:

index.tsx
const tree = jsonToNaryTree(json);
console.log(tree);
54 chars
3 lines

This would output:

index.tsx
[
  {
    "value": "node1",
    "children": [
      {
        "value": "node2",
        "children": []
      },
      {
        "value": "node3",
        "children": []
      }
    ]
  },
  {
    "value": "node4",
    "children": []
  }
]
239 chars
20 lines

gistlibby LogSnag