My CSV data displays pass rates by organisation for different years:
org,org_cat,2004_passed,2004_total,2005_passed,2005_total,2006_passed,2006_total
GSK,industry,35,100,45,100,55,100
I am using D3 and aiming to create a dictionary of organisations structured as follows:
data = {
'GSK': {
'org_cat': 'industry',
'data': [
{ 'year': 2004, 'passed': 35, 'total': 100 },
{ 'year': 2005, 'passed': 45, 'total': 100 },
{ 'year': 2006, 'passed': 55, 'total': 100 }
]
]
}
The process seems clear except for the messy code handling the year columns:
var data = {};
allData.forEach(function(d) {
data[d.org] = {
'category': d.org_cat,
'data': []
};
for (var k in d) {
var temp = {};
for (var k in d) {
if (patt.test(k)) {
var res = k.split("_");
if (res[0] in temp) {
temp[res[0]][res[1]] = +d[k];
} else {
temp[res[0]] = {};
temp[res[0]][res[1]] = +d[k];
}
}
}
var tempArr = [];
for (var y in temp) {
var tempDict = {};
tempDict.year = y;
tempDict.passed = temp[y].passed;
tempDict.total = temp[y].total;
tempArr.push(tempDict);
}
// TODO: sort by year in case the keys got shuffled
data[d.org].data = tempArr;
}
});
Is there a simpler way to clean up this complex code?
We can assume each row represents a unique organisation.