重命名d3.nest()中的键和值 [英] Rename key and values in d3.nest()
问题描述
学习JS数据给出了分组申请与
var expenseMetrics = d3.nest()
.key(function(d) { return d.name; })
.rollup(function(v) { return {
count: v.length,
total: d3.sum(v, function(d) { return d.amount; }),
avg: d3.mean(v, function(d) { return d.amount; })
}; })
.entries(expenses);
console.log(JSON.stringify(expenseMetrics));
导致
[{"key":"jim","values":{"count":2,"total":79,"avg":39.5}},
{"key":"carl","values":{"count":1,"total":120.11,"avg":120.11}},
{"key":"stacy","values":{"count":3,"total":90.9,"avg":30.3}}]
有没有简单从nest转换输出的方法,使键
具有自定义名称,并且值
被展平,产生类似的输出
Is there any easy way to transform the output from nest such that the key
has a custom name and values
is flattened, producing an output like
[{"name":"jim","count":2,"total":79,"avg":39.5},
{"name":"carl","count":1,"total":120.11,"avg":120.11},
{"name":"stacy","count":3,"total":90.9,"avg":30.3}]
这个问题似乎有关,但提供的小提琴的解决方案是难以概括。
This question seems related but the solution in the provided fiddle is hard to generalize.
推荐答案
没有办法 d 3.nest()
这样做(至少不是版本3;在v4中添加的可能性很小,但我对此表示怀疑。)
There's no way to have d3.nest()
do it (at least not in version 3; there's a slight chance it got added in v4, but I doubt it).
但你可以这样做:
var expenseMetrics = d3.nest()
...
.entries(expenses)
.map(function(group) {
return {
name: group.key,
count: group.values.count,
total: group.values.total,
avg: group.values.avg
}
});
如果你想要它更通用,你可以获得与上面相同的输出而无需硬编码任何东西(除了key => name mapping,它适用于硬编码):
If you want it to be more general, you can get the same output as above without hardcoding anything (except the key => name mapping, which is appropriate to hardcode anyway):
var expenseMetrics = d3.nest()
...
.entries(expenses)
.map(function(group) {
var merged = { name: group.key };
// Copy each key-val pair of group.values into merged
Object.keys(group.values).forEach(function(key) {
merged[key] = group.values[key];
});
return merged;
});
这篇关于重命名d3.nest()中的键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!