简体   繁体   中英

Using variables to access nested json keys in d3

I am trying to figure out the best method for accessing nested json data in d3.

So my data looks something like this:

{
    "Florida":{"New York": "yellow",
                "New Jersey": "blue",
                "Pennsylvania": "green",
etc..

And my d3.select function looks something like:

    .selectAll("path")
.style('fill', function(d){
                                    return jsondata.state[d.properties.NAME];

of course, var state here is a variable, which should be referring to "Florida", but doesn't.

The way I see it, there are two ways:

  1. Use some of the parsing methods outlined in this post . Namely, the .get() method

  2. Use d3.nest() in some capacity and rolling up my data into an accessible object ahead of the .style function.

What is the best method?

You can use an ordinal scale, and change its domain and range based on whatever state is selected, and its data.

Create a scale without a domain or range:

var color = d3.scale.ordinal();

Then when a state is selected, get its name, and get the d3.entries for its corresponding object:

var entries = d3.entries(yourData[selectedState]);

Then set the domain and range of the scale to be the keys and values respectively:

color.domain(entries.map(function(d) {return d.key;}));
color.range(entries.map(function(d) {return d.value;}));

Finally, select all of your state paths and use the scale to set the fill:

.selectAll('path').attr('fill', function(d) {return color(d.properties.NAME)})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM