Converting Data Structure Of A Json Array For Stacked Bar Chart
This question is related to a previous question that I asked: Using JSON in d3v4 stacked bar chart. Background: For the stacked bar chart, I am trying to represent a series of hos
Solution 1:
Just create a new dictionary with the key equal to the hospital name. And afterwards retrieve all the elements from the dictionary.
If you need to have the counts as strings convert them just before adding them back to the data list.
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]);
}
}
As a small running example with your huge data set.
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);
Post a Comment for "Converting Data Structure Of A Json Array For Stacked Bar Chart"