Javascript D3.js操作对象数组

时间:2013-08-22 18:21:20

标签: javascript arrays join d3.js javascript-objects

我对javascript或D3.js不是很熟悉,需要一些指导。

我有两个我想加入的数据集(对象数组)。我试图通过“加入”答案将全国平均得分与州平均得分排成一行。要浏览数据,您可以将其剪切并粘贴到Tributary

// National Averages Dataset
var nationaldataset = [];
var nAvg = "http://data.medicare.gov/resource/89u8-shx4.csv"; 
var nscore = "HCAHPS Answer Percent";
var nquestion = "HCAHPS Question";
var nanswer = "HCAHPS Answer Description";

d3.csv( nAvg, function(data)  {
    nationaldataset = data.map(function(d) { return [ d[nquestion], d[nanswer], d[nscore] ]; });
    d3.select("body").selectAll("p")
        .data(nationaldataset)
        .enter()
        .append("p")
        .text( function(d) {return d ;} );  

});
// State Averages Dataset
var statedataset = [];
var sAvg = "http://data.medicare.gov/resource/fhk8-g4vc.csv"; //State Average
var sq1 = "Percent of patients who reported that their nurses \"Sometimes\" or \"Never\" communicated well."
var sq2 = "Percent of patients who reported that their nurses \"Usually\" communicated well."
var sq3 = "Percent of patients who reported that their nurses \"Always\" communicated well."
// .. this list goes on for 30 columns
d3.csv( sAvg, function(data) {
    sstatedataset = data.map(function(d) { return [ d["State"], d[sq1], d[sq2], d[sq3] ]; });
    d3.select("body").selectAll("p")
        .data(statedataset)
        .enter()
        .append("p")
        .text(function(d) {return d ;} );

});

我已经看了几个javascript数组处理方法(Join(),Concatenate()等)但是已经画了一个空白。我将如何做这样的事情 -

Select nationaldataset.nquestion
, nationaldataset.nanswer
, nationaldataset.nscore
, statedataset.Score
From nationaldataset, statedataset 
WHERE nationaldatset.nanswer = statedataset.columnname 
AND statedataset.State in ['SD', 'MN', 'IA'] 

1 个答案:

答案 0 :(得分:1)

遗憾的是,Javascript中没有join运算符或等效运算符 - 您必须明确搜索匹配项。在您的情况下,您可以使用嵌套循环执行此操作。代码看起来像这样。

var results = [];
for(var i = 0; i < statedataset.length; i++) {
  if(statedataset[i].State == "SD" ||
     statedataset[i].State == "MN" ||
     statedataset[i].State == "IA") {
    var j = 0;
    for(j = 0; j < nationaldataset.length; j++) {
      if(nationaldataset[j].nanswer == statedataset[i].columnname) {
        break;
      }
    }
    if(j < nationaldataset.length) {
      results.push({
        "nquestion": nationaldataset[j].nquestion,
        "nanswer": nationaldataset[j].nanswer,
        "nscore": nationaldataset[j].nscore,
        "Score": statedataset[i].Score
      });
    }
  }
}

这应该为您提供可以与D3一起使用的数据结构。是的,这几乎肯定是一种更好的方法。