使用关联数组作为D3的数据

Cru*_*mmy 21 javascript associative-array d3.js

我有一个非常简单的D3示例,首先将数据读入关联数组,然后将其显示在条形图中.

我似乎无法使用此方法显示任何内容.相反,我必须在两者之间插入一个任务:将数据读入关联数组,将数据复制到一个简单数组中,然后使用简单数组显示条形图.

chart.selectAll("div")
     .data(genreAssociative)
     .enter().append("div")
     .style("width", function(d) { return d * 10 + "px"; })
     .text(function(d) { return d; });
Run Code Online (Sandbox Code Playgroud)

以上不起作用.

genreSimple = [];
for (var genre in genreAssociative) genreSimple.push(genreAssociative[genre]);         
chart.selectAll("div")
     .data(genreSimple)
     .enter().append("div")
     .style("width", function(d) { return d * 10 + "px"; })
     .text(function(d) { return d; });
Run Code Online (Sandbox Code Playgroud)

以上呢; 使用简单的数组作为中介.是否有一种特殊的方法来迭代关联数组而不是标准数组?

Lar*_*off 33

您可以使用函数d3.valuesd3.entries直接使用关联数组.您只需要在设置属性的函数中考虑它(例如function(d) { return d.value; }).

  • `d3.entries()`返回一个数组,其中每个元素都有一个`key`和一个`value`成员.您应该能够以这种方式获得键和值. (8认同)
  • 你尝试过使用`.data(d3.entries(genreAssociative))`吗? (2认同)