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

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

问题描述

我确信有一种非常简单优雅的方法可以做到这一点,但我不太明白.我有一些看起来像这样的输入数据:

<预><代码>[{id:1,姓名:彼得"},{id:2,姓名:保罗",经理:1},{id: 3, name: "Mary", manager: 1},{id: 4, name: "John", manager: 2},{id: 5, name: "Jane", manager: 2}]

如果可能,我想使用 d3.js 嵌套运算符来获取要在层次结构布局中使用的结构.像这样:

<预><代码>[{名称:彼得",孩子们:[{姓名:保罗",孩子们:[{姓名:约翰"},{名称:简"}]},{名称:玛丽"}]}]

解决方案

这里不能使用嵌套运算符,因为嵌套会产生固定的层次结构:输出层次结构中的层数与关键函数的数量相同您指定.

也就是说,您可以编写自己的函数来生成一棵树.假设根节点是输入数组的第一个节点,可以创建一个id到node的映射,然后懒惰的构造树.

功能树(节点){var nodeById = {};//按 id 索引节点,以防它们乱序.节点.forEach(函数(d){nodeById[d.id] = d;});//懒惰地计算孩子.节点.forEach(函数(d){如果(d 中的经理"){var manager = nodeById[d.manager];if (manager.children) manager.children.push(d);否则 manager.children = [d];}});返回节点[0];}

如果您知道节点按顺序列出,以便管理器出现在其报告之前,您可以简化代码以仅迭代一次.

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}
]

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.

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:使用嵌套函数将带有父键的平面数据转化为层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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