D3: use nest function to turn flat data with parent key into a hierarchy

前端 未结 1 934
离开以前
离开以前 2020-12-08 09:06

I\'m sure there\'s a really simple elegant way to do this but I can\'t quite figure it out. I have some input data that looks like this:

[
{id: 1, name: \"P         


        
1条回答
  •  执念已碎
    2020-12-08 09:11

    You can't use the nest operator here because nesting produces a fixed hierarchy: the number of levels in the output hierarchy is the same as the number of key functions you specify.

    That said, you can write your own function which produces a tree. Assuming that the root node is the first node in the input array, you can create a map from id to node, and then construct the tree lazily.

    function tree(nodes) {
      var nodeById = {};
    
      // Index the nodes by id, in case they come out of order.
      nodes.forEach(function(d) {
        nodeById[d.id] = d;
      });
    
      // Lazily compute children.
      nodes.forEach(function(d) {
        if ("manager" in d) {
          var manager = nodeById[d.manager];
          if (manager.children) manager.children.push(d);
          else manager.children = [d];
        }
      });
    
      return nodes[0];
    }
    

    If you know that the nodes are listed in order such that managers appear before their reports, you can simplify the code to iterate only once.

    0 讨论(0)
提交回复
热议问题