我将使用Angular 7框架在D3JS库中创建气泡图。因此,我需要嵌套的数据集集合。
我的代码
`this.month_keys = ['January', 'February', 'March', 'April'];
this.nested_data = d3.nest<any, Array<Object>>()
.key(function (d) { return d['username']; })
.rollup(function (leaves) {
return [{
'January': leaves[0]['January'],
'February': leaves[0]['February'],
'March': leaves[0]['March'],
'April': leaves[0]['April']
}];
})
.entries(data);`
我的数据集
[{
April: "6000"
February: "5000"
January: "2500"
March: "7000"
id: "01"
username: "AAAA"
}, and etc.,]
预期结果
[
'key': 'AAAA'
'values': [
{
'name': 'January',
'salary': 85000
},
{
'name': 'February',
'salary': 80000
}
{
'name': 'March',
'salary': 65000
}
]
]
答案 0 :(得分:0)
这里不需要d3.nest
,因为您可以将数据映射为所需的格式(尽管我在代码段中发布了带有d3.nest()的解决方案)。方法如下:
var mapped_data = data.map(function (d) {
return {
key: d['username'],
values: month_keys.map(function (month) {
return {
name: month, salary: d[month]
}
})
}
});
代码段:
var data = [{
April: "6000",
February: "5000",
January: "2500",
March: "7000",
id: "01",
username: "AAAA"
}];
var month_keys = ['January', 'February', 'March', 'April'];
var mapped_data = data.map(function (d) {
return {
key: d['username'],
values: month_keys.map(function (month) {
return {
name: month, salary: d[month]
}
})
}
});
console.log(mapped_data);
console.log("Using d3.nest");
var nested_data = d3.nest()
.key(function (d) { return d.username; }) // key is username
.rollup(function (d) {
// same as the mapping logic but here d would be an array of length 1 (checkout http://learnjsdata.com/group_data.html)
return month_keys.map(function (month) {
return {
name: month, salary: d[0][month]
}
});
}).entries(data);
console.log(nested_data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
希望这会有所帮助。