gpt4 book ai didi

javascript - 重命名 d3.nest() 中的键和值

转载 作者:搜寻专家 更新时间:2023-11-01 05:10:08 31 4
gpt4 key购买 nike

Learn JS Data给出了 split-apply-combine with

的例子
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 的输出,以便 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似乎相关,但提供的 fiddle 中的解决方案很难概括。

最佳答案

没有办法让 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 => name 映射,它无论如何都适合硬编码):

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

关于javascript - 重命名 d3.nest() 中的键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37172184/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com