Reputation: 4496
I am trying to parse data in d3 using the csv function. I am attempting to give each datapoint a new attribute (Region) during processing. Outside the CSV function I defined a function that is supposed to take the datapoint, check to see if the state is Alabama, and if so, assign the Region attribute to a string of either "North" or "South".
var parseRegion = (function(d){
if(d.State === "Alabama"){
return "South";
}
else {
return "North";
}
});
However, when I run the code, every datapoint is assigned a "Region" attribute that is assigned to the function itself. In other words, it is assigned the actual code, rather than the return values. What am I doing wrong??
d3.csv("data.csv").get(function(error,data){
if (error) throw error;
data.forEach(function(d){
d.Deaths = +d.Deaths;
d.Population = +d.Population;
d.Year = parseDate(d.Year);
d.Region = parseRegion;
});
Thanks for any help you can provide. Eventually I will add additional states besides Alabama of course.
Upvotes: 0
Views: 239
Reputation: 11557
Your problem is that you're not calling the parseRegion function that you define.
So you need
d.Region = parseRegion(d);
More generally d3.csv
provides a way to parse the data without the use of forEach
. You can do the following:
d3.csv("data.csv")
.row(function(d) {
//Code to parse data row by row goes here
})
.get(function(error,data){
//Data is now the whole parsed dataset
});
Upvotes: 2