问题
I have a very simple D3 example that first reads data into an associative array, then displays it in a bar graph.
I can't seem to get anything to display using this method though. Instead, I have to insert a task in between: Read the data into an associative array, copy that data into a simple array, then display the bar graph using the simple array.
chart.selectAll("div")
.data(genreAssociative)
.enter().append("div")
.style("width", function(d) { return d * 10 + "px"; })
.text(function(d) { return d; });
The above does not work.
genreSimple = [];
for (var genre in genreAssociative) genreSimple.push(genreAssociative[genre]);
chart.selectAll("div")
.data(genreSimple)
.enter().append("div")
.style("width", function(d) { return d * 10 + "px"; })
.text(function(d) { return d; });
The above does; using a simple array as an intermediary. Is there a special way to iterate over an associative array instead of a standard array?
回答1:
You can use the functions d3.values or d3.entries to work directly with associative arrays. You simply need to take it into account in the functions that set attributes (e.g. function(d) { return d.value; }).
回答2:
I found that in order for bar chart generation to work well, the following format works best. It's based on the the D3 post-parsed CSV format.
var dataSet1 = [
{xCoordinate: "Legend String 1", magnitude: 54, link: "http://www.if4it.com"},
{xCoordinate: "Legend String 2", magnitude: 21, link: "http://www.if4it.com/glossary.html"},
{xCoordinate: "Legend String 3", magnitude: 31, link: "http://www.if4it.com/resources.html"},
{xCoordinate: "Legend String 4", magnitude: 14, link: "http://www.if4it.com/taxonomy.html"},
{xCoordinate: "Legend String 5", magnitude: 19, link: "http://www.if4it.com/disciplines.html"},
{xCoordinate: "Legend String 6", magnitude: 47, link: "http://www.if4it.com"},
{xCoordinate: "Legend String 7", magnitude: 27, link: "http://www.if4it.com/glossary.html"}];
The format allows for the correlation of coordinates, magnitudes, legends and html links to each other.
A working example can be found at: http://bl.ocks.org/2164562.
来源:https://stackoverflow.com/questions/9589768/using-an-associative-array-as-data-for-d3