gpt4 book ai didi

javascript - 为堆叠条形图转换 JSON 数组的数据结构

转载 作者:行者123 更新时间:2023-11-30 20:19:34 25 4
gpt4 key购买 nike

这个问题与我之前提出的一个问题有关:Using JSON in d3v4 stacked bar chart .

背景:对于堆积条形图,我试图表示一系列医院,这些医院显示每位患者的诊断所属的类别总数(针对每家医院)。我使用 SQL 查询生成了我的 JSON 文件并将其导出。

问题:如何更改我的 JSON 数组数据结构以合并同一家医院的多个类别?

我的堆叠条形图的 JSON 数组数据结构(一小部分)如下所示:

[{
"hospitalName": "hospital1",
"category": "Injury & Poisoning",
"Females": "0",
"Males": "4",
"Unknown": "0",
"count": "4"
},
{
"hospitalName": "hospital1",
"category": "Symptoms, Signs, & Ill-Defined Conditions",
"Females": "1",
"Males": "1",
"Unknown": "0",
"count": "2"
},
{
"hospitalName": "hospital2",
"category": "Mental Disorders",
"Females": "0",
"Males": "1",
"Unknown": "0",
"count": "1"
}]

所需的 JSON 数组数据结构:

[{
"hospitalName": "hospital1",
"Injury & Poisoning": "4",
"Symptoms, Signs, & Ill-Defined Conditions": "2"
"Females": "1", <--- the count of females is increased
"Males": "5", <--- the count of males is increased
"Unknown": "0",
"count": "6"
},
{
"hospitalName": "hospital2",
"category": "Mental Disorders",
"Females": "0",
"Males": "1",
"Unknown": "0",
"count": "1"
}]

这是否可以使用 SQL 查询生成,或者我可以使用 PLSQL 代替吗?

最佳答案

只需创建一个新字典,键等于医院名称。然后从字典中检索所有元素。

如果您需要将计数转换为字符串,然后再将它们添加回数据列表。

var newdata = {};

data.forEach(element => {
var name = element.hospitalName;
var hospital = newdata[name];
if (!hospital) {
hospital = { hospitalName: name, Females: 0, Males: 0, Unknown: 0, count: 0};
newdata[name] = hospital;
}
hospital[element.category] = +element.count;
hospital.Females += +element.Females;
hospital.Males += +element.Males;
hospital.Unknown += +element.Unknown;
hospital.count += +element.count;
});

data = [];

for (const key in newdata) {
if (newdata.hasOwnProperty(key)) {
data.push(newdata[key]);
}
}

作为您的庞大数据集的一个小型运行示例。

var data = [{
"hospitalName": "hospital1",
"category": "Injury & Poisoning",
"Females": "0",
"Males": "4",
"Unknown": "0",
"count": "4"
},
{
"hospitalName": "hospital1",
"category": "Symptoms, Signs, & Ill-Defined Conditions",
"Females": "1",
"Males": "1",
"Unknown": "0",
"count": "2"
},
{
"hospitalName": "hospital2",
"category": "Mental Disorders",
"Females": "0",
"Males": "1",
"Unknown": "0",
"count": "1"
}];

var newdata = {};

data.forEach(element => {
var name = element.hospitalName;
var hospital = newdata[name];
if (!hospital) {
hospital = { hospitalName: name, Females: 0, Males: 0, Unknown: 0, count: 0};
newdata[name] = hospital;
}
hospital[element.category] = +element.count;
hospital.Females += +element.Females;
hospital.Males += +element.Males;
hospital.Unknown += +element.Unknown;
hospital.count += +element.count;
});

data = [];

for (const key in newdata) {
if (newdata.hasOwnProperty(key)) {
data.push(newdata[key]);
}
}

console.log(data);

关于javascript - 为堆叠条形图转换 JSON 数组的数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51599670/

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