I'm sorry if this is duplicated but I'm trying to sum values from a JSON output, I'm able to sum the values from one property, but I need to sum the values that match the month for each property, any help is appreciated,
let json =
{
"months":[
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov"
],
"data":{
"label":[
{
"Electricity":[
{
"total_bill":"84.54",
"due_date":"2020-06-30"
},
{
"total_bill":"62.38",
"due_date":"2020-07-30"
}
]
},
{
"Gas":[
{
"total_bill":"133.26",
"due_date":"2020-06-29"
},
{
"total_bill":"120.25",
"due_date":"2020-07-30"
}
]
}
]
}
}
For example I want to add the total_bill for Electricty and Gas for June (2020-06), and sum the total_bill for July (2020-07), please ignore the months array, it is used only to display the information in a chart graphic.
Edit:
What I've tried so far is:
let labels = [];
//Get labels name, eg. Electriciy, Gas, Water, etc
for(let i = 0; i < json.data.label.length; i++) {
labels.push(Object.keys(json.data.label[i]).toString());
}
//Tried to sum them but only figure out how to sum for the same property
let temp = [];
for (let i = 0; i < json.data.label.length; i++) {
let str = labels[i];
let values = json.data.label[i][str];
let sum = 0;
for (let j = 0; j < values.length; j++) {
sum = sum + Number(values[j].total_bill);
}
temp.push(sum);
}
//Desired output is:
//84.54 + 133.26 and 62.38+120.25
temp = [217.8,182.63];
Thanks so much for looking into this and for your help
Loop edit:
Ok after playing around with the loop, I was able to find the one that sum the values and returns the desired output, thanks
for (let i = 0; i < json.data.label.length; i++) {
let sum = 0;
for (let j = 0; j < json.data.label.length; j++) {
sum = sum + Number(json.data.label[j][labels[j]][i].total_bill);
}
temp.push(sum);
}
console.log(temp); // [217.8, 182.63]