Reputation: 549
Looking to make a map visualization. Wanted a simple key-value object in this format:
{
Alabama: "AL",
Alaska: "AK",
Arizona: "AZ",
...
}
Read data as such:
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>
Try to run this snippet. It seems to be grabbing the right data points but not populating the stateCodes
object or not returning it.
What should I change?
Upvotes: 2
Views: 725
Reputation: 8509
You put your console.log
after d3.csv
method which is asynchronous. Move it after d3.map
and check that stateCodes
was populated:
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
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.min.js"></script>
Pay attention that in your data file California
has a space character at the beginning.
You can fix it in source file or use trim
method:
stateCodes[d["state"].trim()] = d["code"];
;
Upvotes: 1