My main objective is to construct a d3 stacked diverging bar chart. The issue I'm facing is that even though the votesData array is successfully created from the data, I can only access this data within the d3 then function where it's generated.
Sample Code:
var votesData = [];
//fetching data from votes route
d3.json("/votes").then(function (data) {
//iterating through objects in the route
data.forEach(function (d) {
//converting data to numeric values
demYes = +d.democratic.yes
demNo = ~d.democratic.no
repYes = +d.republican.yes
repNo = ~d.republican.no
indYes = +d.independent.yes
indNo = ~d.independent.no
//appending necessary data to votesData array
votesData.push(
{"name": d.bill.bill_id,
"question": d.question,
"description": d.description,
"votes": [
{"category": "Democratic Yes",
"value": demYes },
{"category": "Democratic No",
"value": demNo},
{"category": "Republican Yes",
"value": repYes},
{"category": "Repulican No",
"value": repNo},
{"category": "Independent Yes",
"value": indYes},
{"category": "Independent No",
"value": indNo}
]
})
});
console.log(votesData);
console.log(votesData[0]);
});
console.log(votesData);
console.log(votesData[0]);
The initial log outputs return the expected array and first object, however, when attempting to access the object outside the d3 then function, the second logs display the votesData object but trying to retrieve the first index results in "undefined". Why is this happening? Is there a way to loop through this object outside of the d3 then function? Or is it recommended to include everything needed within the svg area inside that function?