使用d3.csv读取键值对

时间:2017-11-20 07:12:50

标签: javascript csv d3.js dataframe

希望制作地图可视化。想要这种格式的简单键值对象:

 {
      Alabama: "AL",
      Alaska: "AK",
      Arizona: "AZ",
      ...
 }

读取数据:



    var source = "https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv";
    
    var stateCodes = {};
    
    d3.csv(source, data => {
        data.map(d => {
            stateCodes[d["state"]] = d["code"];
            return stateCodes;   
        }); 
    });

    console.log(stateCodes);

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.min.js"></script>
&#13;
&#13;
&#13;

尝试运行此代码段。它似乎抓住了正确的数据点,但没有填充stateCodes对象或不返回它。

我应该改变什么?

1 个答案:

答案 0 :(得分:1)

您将console.log置于异步d3.csv方法之后。在d3.map之后移动它并检查是否填充了stateCodes

Docs for d3.csv method

&#13;
&#13;
var source = "https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv";
    
var stateCodes = {};
    
d3.csv(source, (data) => {
    data.map(d => {
        stateCodes[d["state"]] = d["code"];
        return stateCodes;   
    });
 
    console.log(stateCodes);
    // other code
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.min.js"></script>
&#13;
&#13;
&#13;

请注意,数据文件中California的开头有空格字符。

enter image description here

您可以在源文件中修复它或使用trim方法:

stateCodes[d["state"].trim()] = d["code"];;