过滤json数据,然后使用d3.nest

时间:2015-07-05 06:15:32

标签: javascript json d3.js

我正在尝试了解如何过滤json数据,然后创建一个包含过滤数据的表。

我开始看这个街区: https://gist.github.com/mbostock/844752

这正是我想要的那种表。

然后我在过滤时看到了这个stackexchange帖子:D3 filtering data points

我用它作为我添加的过滤功能的模板。有用! 但是,现在我似乎无法使嵌套工作,因为返回的过滤数据具有每个对象的键。

在控制台中它看起来像这样:

[6: Object, 7: Object, 34: Object, 35: Object, 36: Object] 

而未经过滤的数据如下所示:

[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]

如果有人有任何想法如何访问过滤数据中的“国家/地区”键,那将非常有用!我一直在寻找,但没有找到答案。如果我能澄清,请告诉我。

这是我正在使用的代码:

<!DOCTYPE html>
<html>
  <head>
     <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
  </head>
<body>
<table id="countries">
</table>
<script type="text/javascript"> 

function filterJSON(json, key, value) {
      var result = [];
      for (var indicator in json) {
        if (json[indicator][key] === value) {
          result[indicator] = json[indicator];
        }
      }
      return result;
    }

d3.json("nest.json", function(json) {

filtered = filterJSON(json, 'Aspect', 'Economy');
console.log(filtered);
console.log(json);

var datanest = d3.nest()
        .key(function(d) { return d.Country; })
        .sortKeys(d3.ascending)
        .map(json); // this is the nest that works, using the full json file.

var nestfilt = d3.nest()        
        .key(function(d) { return d.Country; })
        .sortKeys(d3.ascending)
        .map(filtered); // this is the nest that does not work. 

var tr = d3.select("#countries")
  .selectAll("tr")
  .data(d3.entries(datanest))
 .enter().append("tr");

tr.append("th")
  .text(function(d) { return d.key; });

tr.selectAll("td")
  .data(function(d) { return d.value; })
  .enter().append("td")
  .text(function(d) { return d.Aspect + ":  " + d.Value + ", " + d.Year; });

});

</script>

1 个答案:

答案 0 :(得分:1)

您可以将filterJSON更改为result.push(json[indicator])而不是result[indicator] = json[indicator]吗?这样,result就是一个数组,并且格式与未经过滤的数据相同。

以下是jsfiddle中的示例。它似乎有效,除了未定义年份,因为我认为我的样本数据与您的不同。