Reputation: 59
Im currently trying to build a choropleth on the map of Puerto Rico using D3. Using Scott Murray's Example on Choropleths, I'm trying to bind data to each municipality of Puerto Rico. I have a placeholder empty object to hold the data being fed from the CSV like so:
var properties = {};
Then, I proceed to read the CSV file by row. I assign the corresponding values to some variables like so:
properties.dataID = parseFloat(data[i].id);
properties.dataMunic_Total = parseFloat(data[i].municipio_total);
//etc.
All fine and dandy. I console.log to check whether or not the data was stored correctly:
console.log(properties.dataID);
//Displays 1, which is correct.
However, when I try to access the whole object:
console.log(properties);
it only displays the last row of the CSV file. I ran that last console.log() statement inside the first for loop, immediately after assigning the data to the object's properties, and every time the loop iterates through the console.log(), it ONLY displays the last line of the CSV file.
When I try to assign the object properties to my map's objects (municipalities), all that it ever assigns is that last line of the CSV file. So I tried setting them up individually, seeing that seems to have worked. However, JavaScript complains that the property does not exist in the object:
obj.geometries[j].properties.year[properties.dataYear - 2000].id = properties.dataID;
Uncaught TypeError: Cannot read property 'id' of undefined
I tried initializing it as if it were a new variable:
var obj.geometries[j].properties.year[properties.dataYear - 2000].id = properties.dataID;
but then I got this back on the console:
Uncaught SyntaxError: Unexpected identifier
Aside from the syntax error, I think that this is mainly due to the fact that I appended an array to each municipality so I could hold different sets of data per year... but I don't understand why JavaScript behaves this way.
My question is: why does my object behave this way? Is there something wrong with d3.csv? Am I doing something wrong?
Upvotes: 0
Views: 455
Reputation: 109252
If you want to store several properties, you need to use an array (i.e. a list). In the code you are using, you are only creating a single variable properties
at a time and not saving the references to the ones you have created previously. That is, in each iteration of the loop, you are creating a new object, but losing the old one.
If you declare properties
as an array and then append new property objects in the loop, you can reference them later and use them to draw the map. The code would look something like this.
var properties = [];
for(var i = 0; i < data.length; i++) {
var property = {};
property.dataID = parseFloat(data[i].id);
property.dataMunic_Total = parseFloat(data[i].municipio_total);
// ...
properties.push(property);
}
After setting up the data like this, you should be able to proceed as described in the example.
Upvotes: 1