D3:使用nest函数将带有父键的平面数据转换为层次结构 [英] D3: use nest function to turn flat data with parent key into a hierarchy

查看:221
本文介绍了D3:使用nest函数将带有父键的平面数据转换为层次结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确定有一个非常简单的优雅的方式来做到这一点,但我不能完全弄清楚。我有一些输入数据,如下所示:

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: "Peter"},
{id: 2, name: "Paul", manager: 1},
{id: 3, name: "Mary", manager: 1},
{id: 4, name: "John", manager: 2},
{id: 5, name: "Jane", manager: 2}
]

如果可能,我想使用d3.js nest操作符来获得在层次结构布局中使用的结构。像这样:

If possible, I would like to use the d3.js nest operator to get a structure to use in the hierarchy layout. Like this:

[ 
   {name: "Peter", children: [
          {name:"Paul", children: [
              {name:"John"},
              {name:"Jane"}
          ]},
          {name:"Mary"}
      ]
   }
]


推荐答案

您不能在此处使用嵌套运算符,因为嵌套会生成固定的层次结构:输出层次结构中的级别数与您指定的键函数数相同。

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.

也就是说,你可以编写自己的函数产生一个树。假设根节点是输入数组中的第一个节点,您可以创建一个从id到节点的映射,然后懒惰地构造树。

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.

这篇关于D3:使用nest函数将带有父键的平面数据转换为层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆