Last active
August 29, 2015 14:04
-
-
Save halsk/829fb19980af48087c70 to your computer and use it in GitHub Desktop.
D3.js で csvのforEach
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<!-- | |
D3.js でこんなことをやりたいらしい。 | |
【BEFORE】 | |
Prefecture,教授,芸術,宗教,報道,投資・経営 | |
北海道,249,6,207,0,152 | |
青森,19,0,19,0,17 | |
【AFTER】 | |
[Prefecture: 北海道, | |
values : [ | |
{key: 教授, value: 249}, | |
{key: 芸術, value: 6}, | |
{key: 宗教, value: 207}, | |
{key: 報道, value: 0}, | |
{key: 投資・経営, value: 152} | |
], | |
[Prefecture: 青森, | |
values : [ | |
{key: 教授, value: 19}, | |
{key: 芸術, value: 0}, | |
{key: 宗教, value: 19}, | |
{key: 報道, value: 0}, | |
{key: 投資・経営, value: 17} | |
]] | |
とりあえず素直に書いてみた | |
--> | |
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> | |
<script> | |
d3.csv("data.csv", function(data) { | |
var json_data = data.map(function(d){ | |
var row = null; | |
for (var c in d){ | |
if (!row){ //一行目だけ直接属性に | |
row = {}; | |
row[c] = d[c]; | |
row.values = []; | |
}else{ //その他は値に | |
row.values.push({key: c, value: d[c]}); | |
} | |
} | |
return row; | |
}); | |
console.log(JSON.stringify(json_data)); | |
}); | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment