我想使用 d3.nest()
创建 JSON 的键值对。
原始 JSON 如下所示:
[
{
"Country": "Mexico",
"Climate": 100,
"Safety Index": 50,
"Life Expectancy": 80,
"Corruption": 30,
"Per Capita Income": 20
},
{
"Country": "UK",
"Climate": 70,
"Safety Index": 80,
"Life Expectancy": 70,
"Corruption": 70,
"Per Capita Income": 80
},
{
"Country": "US",
"Climate": 80,
"Safety Index": 70,
"Life Expectancy": 90,
"Corruption": 70,
"Per Capita Income": 80
}
]
我想把它改成这样:
[
{"key": "Mexico", "value":
[
{ "key": "Climate", "value": 100 },
{ "key": "Safety Index", "value": 50 },
{ "key": "Life Expectancy", "value": 80 },
{ "key": "Corruption", "value": 30 },
{ "key": "Per Capita Income", "value": 20 }
]},
{"key": "UK", "value":
[
{ "key": "Climate", "value": 70 },
{ "key": "Safety Index", "value": 80 },
{ "key": "Life Expectancy", "value": 70 },
{ "key": "Corruption", "value": 70 },
{ "key": "Per Capita Income", "value": 80 }
]},
{"key": "US", "value":
[
{ "key": "Climate", "value": 80 },
{ "key": "Safety Index", "value": 70 },
{ "key": "Life Expectancy", "value": 90 },
{ "key": "Corruption", "value": 70 },
{ "key": "Per Capita Income", "value": 80 }
]}
]
我的尝试:
var nest = d3.nest()
.key(function(d) { return d.Country; })
.entries(data);
我的问题非常基本,因为我是 D3 的新手。我应该如何更改 D3 中的 JSON 结构?
编辑
这是根据与此示例类似的不同类别为每个国家/地区创建单独的条形图 ( http://bl.ocks.org/mbostock/5872848 )。如果我有更好的方法来思考这个问题,请告诉我。
最佳答案
如果您想要所提供的精确输出,并坚持为此使用嵌套,您可以使用:
var nest = d3.nest()
.key(function(d) { return d.Country; })
.rollup(function(d) {
var countryGroupedObject = d[0];
return d3.nest()
.key(function(innerKey) { return innerKey; })
.rollup(function(innerKey) { return countryGroupedObject[innerKey]; })
.entries(Object.keys(countryGroupedObject));
})
.entries(data);
这里的一个潜在问题是您假设每个国家/地区都是唯一的(例如,不会有两个“墨西哥”条目)。因此,内部嵌套仅在 d[0]
上运行(这将是针对给定国家/地区列出的第一个项目)。
编辑:实际上,这不完全是您所要求的,国家键:值将存在于内部分组中。如果这是一个问题,可以通过在内嵌套之前放置以下内容来忽略它:
删除countryGroupedObject.Country;
编辑2:上面的代码使用嵌套的nest
函数只是因为问题是这样问的。在实际系统中,内部嵌套对我来说更有意义是纯 Javascript,大致如下:
function getGraphParams(countryObj){
return Object.keys(countryObj)
.filter(function(key){ return key !== "Country"; })
.map(function(key){ return { key: key, value: countryObj[key] }; })
}
关于javascript - 通过 D3 中的嵌套为 JSON 创建键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31343176/