Learn JS Data给出了split-apply-combine与
的例子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}}]
是否有任何简单的方法来转换嵌套的输出,使key
具有自定义名称并且values
被展平,产生类似
[{"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似乎有关系,但提供的小提琴中的解决方案很难概括。
答案 0 :(得分:8)
没有办法让d3.nest()
这样做(至少在版本3中没有;在v4中添加它的可能性很小,但我对此表示怀疑)。
但你可以这样做:
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 =>名称映射,这适用于硬编码):
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;
});