2014-03-03 345 views
0

我正在使用數據映射並希望能夠從csv文件讀取數據。將csv讀取到d3對象的對象[數據映射]

該數據地圖期待的數據格式如下:

var loadeddata = { 
    "JPN":{Rate:17.5,fillKey:"firstCat"}, 
    "DNK":{Rate:16.6,fillKey:"secondCat"} 
    }; 

我想閱讀下列結構的CSV文件,並將其轉換成數據地圖期待的格式:

ISO, Rate, fillKey 
JPN, 17.5, firstCat 
DNK, 16.6, secondCat 

我的「最好的企圖」用下面的代碼:

var csvloadeddata; 

d3.csv("simpledata.csv", function (error, csv) { 
    if (error) return console.log("there was an error loading the csv: " + error); 
    console.log("there are " + csv.length + " elements in my csv set"); 

    var nestFunction = d3.nest().key(function(d){return d.ISO;}); 

    csvloadeddata = nestFunction.entries(
         csv.map(function(d){ 
            d.Rate = +d.Rate; 
            d.fillKey = d.fillKey; 
            return d; 
           }) 
        ); 
    console.log("there are " + csvloadeddata.length + " elements in my data"); 
}); 

但這種合作de生成如下所示的變量'csvloadeddata':

var csvloadeddata = [ 
     {"key": "JPN", "values": { 0: {Rate:17.5, fillKey:"firstCat"}} }, 
     {"key": "DNK", values : { 1: {Rate:16.6,fillKey:"secondCat"}} } 
    ]; 

我在做什麼錯了?

+0

高興你理解了它。你可以發佈你的解決方案作爲答案(一旦系統允許你接受它),所以這顯示爲一個回答問題? – AmeliaBR

+0

謝謝你告訴我!就這樣做了! – user2656065

回答

0

我自己找到答案。如果有人有興趣 - 這就是我最終使用:

<script> 
d3.csv("simpledata.csv", function(error, csvdata1) { 

    globalcsvdata1 = csvdata1; 

    for (var i=0;i<csvdata1.length;i++) 
     { 
       globalcsvdata1[ globalcsvdata1[i].ISO] = globalcsvdata1[i] ; 
       //console.log(globalcsvdata1[i]); 
       delete globalcsvdata1[i].ISO; 
       delete globalcsvdata1[i] ; 
      } 
myMap.updateChoropleth(globalcsvdata1); 

} 

); 



var myMap = new Datamap({ 
    element: document.getElementById('map'), 
    scope: 'world', 
    geographyConfig: { 
     popupOnHover: true, 
     highlightOnHover: false 
    }, 
    fills: { 
     'AA': '#1f77b4', 
     'BB': '#9467bd', 
     defaultFill: 'grey' 
    } 


}); 



    </script> 
</body> 

的CSV結構如下:

ISO,fillKey 
RUS,AA 
USA,BB 

這裏是一個工作示例:http://www.explainingprogress.com/wp-content/uploads/datamaps/uploaded_gdpPerCapita2011_PWTrgdpe/gdpPerCapita2011_PWTrgdpe.html