Search code examples
javascriptjsond3.jsdynamic-arrays

JSON to Javascript hierarchy (array?)


I would like to use the hierarchical structure of JSON, in a d3 tree layout such as in:

http://bl.ocks.org/1249394

In my work, I am using a variable in javascript:

var treeData = {
  "name" : "A1", "children" : [
    {"name" : "A3", "children": [
      {"name" : "A31", "children" :[
        {"name" : "A311" },
        {"name" : "A312" }
      ]}
    ]}
  ]};

How do I use this hierarchy as a dynamic javascript array, so that values can be pulled and new layers/branches in the hierarchy can be added or removed dynamically? Does this require a loop or empty arrays? I want to be able to create this hierarchy. My main problem is that I don't know how to keep the hierarchical structure in the javascript array code.


Solution

  • If I understand your question correctly, after you assign value to treeData as you did above, it's already the hierachy you want. To manipulate them easier, you can do something like

    tree.nodes(treeData);
    

    to get an array of objects