gpt4 book ai didi

javascript - d3 关于如何对值求和

转载 作者:数据小太阳 更新时间:2023-10-29 05:14:33 27 4
gpt4 key购买 nike

我有以下数据:

[
{ id: 0, Department: "Civil", Value: "40000", Title:"Sustainability", ComID: "45", organisation: { City: "New York", ComID: 45, Country: "USA" } },
{ id: 1, Department: "Energy", Value: "82000", Title: "Wind Energy", ComID: "62", organisation: { City: "Paris" , ComID: 62, Country: "France" } },
{ id: 2, Department: "Medical", Value: "67000", Title: "Neuroscience", ComID: "21", organisation: { City: "Berlin", ComID: 21, Country: "Germany" } },
{ id: 3, Department: "Computer", Value: "100000", Title: "Security", ComID: "67", organisation: { City: "Amsterdam", ComID: 67, Country: "Holland" } }
]

数据是一个包含大约 100 个对象的数组,如上所示。

在数据中我有同一个国家的组织。我想将每个国家/地区的 Value 属性相加并放入一个新表中。

例如我想创建:

[ { Name: "each Country", Value: "the summed value" } ]

最佳答案

编辑以回应更新的问题

您可以使用 d3.nest()按给定键(在本例中为国家/地区)对对象进行分组,然后“将它们汇总”以对属于给定国家/地区的每个项目的值(value)求和。在您的情况下,单线看起来像这样:

d3.nest().key(function(d){
return d.organisation.Country; })
.rollup(function(leaves){
return d3.sum(leaves, function(d){
return d.Value;
});
}).entries(data)
.map(function(d){
return { Country: d.key, Value: d.values};
});

我在这里使用 d3.sum ,传入访问器函数以指定您要对每个项目的 Value 求和:

这会根据您的示例数据返回四个对象:

[{"Country":"USA","Value":40000},
{"Country":"France","Value":82000},
{"Country":"Germany","Value":67000},
{"Country":"Holland","Value":100000}]

Javascript 为您将字符串转换为数字。请注意,您的示例数据中有一些我必须修复的拼写错误,给出以下内容:

var data = [ { id:0,Department: "Civil",Value : "40000",Title :"Sustainability",ComID : "45", organisation:{ City:"New York",ComID:"45",Country: "USA"}}, { id:1,Department: "Energy",Value : "82000",Title : "Wind Energy",ComID : "62", organisation:{ City:"Paris",ComID:"62",Country: "France"}}, { id:2,Department: "Medical",Value : "67000",Title : "Neuroscience",ComID : "21", organisation:{ City:"Berlin",ComID:"21",Country: "Germany"}}, { id:3,Department: "Computer",Value : "100000",Title : "Security",ComID : "67", organisation:{ City:"Amsterdam",ComID:"67",Country: "Holland"}}]

关于javascript - d3 关于如何对值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40206410/

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