score:15

Accepted answer

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.


Related Query

More Query from same tag