javascript - 如何将数据添加到数据位于父对象的父对象中的 selectAll 占位符?

标签 javascript d3.js

最初,我有一个来自 csv 的平面哈希结构,其中包含以下字段:

zoneId,op,metricName,value

然后我将其嵌套

d3.nest()
  .key(function(d){return d.zoneId})
  .key(function(d){return d.op})
  .entries(data)

现在它有一个看起来像的层次结构

zoneId -> op -> <details>

这是数据示例

nestedData = {
[{
  "key": "zone1",
  "values": [{
    "key": "Get",
    "values": [{
      "zoneId":"zone1"
      "op":"Get"
      "metricName":"CompletionTime",
      "value":"10ms"
    }, {
      "zoneId":"zone1"
      "op":"Get"
      "metricName":"Throughput",
      "value":"100 query/s"
    }]
  },{
    /* Similar to the "values" of last bracket */
    }]
  }]
}, {
  "key": "zone2",
  "values": [
    /* Similar to the "values" of last bracket */
    ]
  }]
}]
}

现在我想从这个嵌套数据结构构建一个表。

  • 每个区域占用一张 table
  • 每个操作都是一行
  • 每行
    • 左列是操作名称
    • 右列是指标的格式化版本(例如:“10 ms @ 100 QPS”)

问题是:

我应该如何将数据绑定(bind)到 占位符?由于

有数据,但当我将它们附加到
时 没有数据,而 位于 下。

var tables = d3.select('#perfs .metrics')
          .selectAll('table')
          .data(nestedData)
          .enter().append('table');
/* added tbody and data */
tables.append('tbody')
      .selectAll('tr')
      .data(???).enter()
      .append('tr')
      .selectAll('td')
      .data(function(d){return [d.key,d.value];})   // left and right column
      .enter().append('td')
      .text(function(d){ /* iterate through the metrics and format them */ })

这是我能想到的两种解决方案:

  • 将数据分配给 tbody(但听起来很老套!)
  • 访问 this.parentNode.__data__ (也听起来很黑客!)

你能给点建议吗?

最佳答案

如果你看<a href="https://github.com/mbostock/d3/wiki/Selections#wiki-append" rel="noreferrer noopener nofollow">selection.append()</a>API ,内容如下:

Each new element inherits the data of the current elements

换句话说,<tbody>默认情况下将具有绑定(bind)到 <table> 的相同数据。因此,您的代码将是:

var metrics = d3.select('#perfs .metrics');
var tables = metrics.selectAll('table').data(nestedData);
tables.enter().append('table');

var tbody = tables.append('tbody');
var rows = tbody.selectAll("tr").data(function(d) { return d.values; });
rows.enter().append("tr");
var cells = rows.selectAll("td").data(function(d) { return d.values; });
cells.enter().append("td")
  .text(function(d){ /* iterate through the metrics and format them */ });

关于javascript - 如何将数据添加到数据位于父对象的父对象中的 selectAll 占位符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12699265/