简体   繁体   English

使用变量访问D3中的嵌套JSON键

[英]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. 我试图找出在d3中访问嵌套json数据的最佳方法。

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: 我的d3.select函数看起来像:

    .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. 当然,这里的var state是一个变量,应引用“佛罗里达”,但不是。

The way I see it, there are two ways: 我看到的方式有两种:

  1. Use some of the parsing methods outlined in this post . 使用一些概括的分析方法, 在这个岗位 Namely, the .get() method 即.get()方法

  2. Use d3.nest() in some capacity and rolling up my data into an accessible object ahead of the .style function. 以某种能力使用d3.nest(),然后将数据汇总到.style函数之前的可访问对象中。

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: 然后,在选择状态时,获取其名称,并获取其对应对象的d3.entries

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)})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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