bisamov
bisamov

Reputation: 730

D3.js nest function, cannot get data into hierarchy

So I am trying to create d3.js tree. My data must be in the hierarchical form before it can be passed to d3.treeLayout.

at this moment here how my json array looks like

var data = [
      {"group":"1","price":"36599.88", "cy":"44260"},
      {"group":"2","price":"36599.88", "cy":"44260"},
      {"group":"3","price":"36599.88", "cy":"44260"},
      {"group":"4","price":"36599.88", "cy":"44260"},
      {"group":"1","price":"1241.88", "cy":"44260"},
      {"group":"2","price":"36595429.88", "cy":"44260"},
      {"group":"3","price":"12124.88", "cy":"44260"},
      {"group":"4","price":"6264.88", "cy":"44260"},
    ]

And I use d3.nest() function that must group the entries

var NestedBudget = d3.nest()
                    .key(function(d){
                        return d.group;
                    })
                    .entries(data);

However, this data is not working when i further pass it to d3.hierarchy(). enter image description here

I attached the picture of the outcome I receive after I pass it to var root_data = d3.hierarchy(data);

I hope I didn't confuse anyone. Any help will be appreciated

Upvotes: 0

Views: 670

Answers (2)

bisamov
bisamov

Reputation: 730

Ok, so what Pierre Capo said was right. I added var packableData = {id:"parent", values:data};

to the data I am receiving and that will set the parent in the hierarchy when you pass it to d3.hierarchy()

Upvotes: 0

Pierre Capo
Pierre Capo

Reputation: 1053

Remember that you want to have a tree. A tree needs to have a root element and every node needs 2 things : an unique id, and a field which links to his parent's id.

For instance, with the data that you have, by adding an id field and assuming that "group" represent the parent node, you can transform your flat data into a hierarchical one :

var data = [
      {"id":"0", "group":null, "price":"36599.88", "cy":"44260"},
      {"id":"1", "group":"0", "price":"36599.88", "cy":"44260"},
      {"id":"2", "group":"0","price":"36599.88", "cy":"44260"},
      {"id":"3", "group":"0","price":"36599.88", "cy":"44260"},
      {"id":"4", "group":"0","price":"36599.88", "cy":"44260"},
      {"id":"5", "group":"1","price":"1241.88", "cy":"44260"},
      {"id":"6", "group":"2","price":"36595429.88", "cy":"44260"},
      {"id":"7", "group":"3","price":"12124.88", "cy":"44260"},
      {"id":"8", "group":"4","price":"6264.88", "cy":"44260"},
    ];
    
const tree = d3
      .stratify()
      .id(d => d.id)
      .parentId(d => d.group)(data);
      
console.log(tree);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

Note that the node with the "group":null is the root node (by definition a root node is the starting node of your tree, so it doesn't have any parent).

Upvotes: 1

Related Questions