0

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]
5
  • What have you tried so far in order to achieve your desired result ? Commented Jun 17, 2020 at 8:58
  • I'm able to extract the total_bill and sum them for each property (eg Electricty, 84.54 + 62.38) with a loop, but I'm wondering how to sum the Electricity bill and the Gas bill, the output is dynamically generated. Commented Jun 17, 2020 at 9:08
  • 2
    Please add you code plus the desired output. Commented Jun 17, 2020 at 9:13
  • 1
    Do you want the sum per month? Commented Jun 17, 2020 at 9:38
  • Yes, that's it exactly what I'm looking for Commented Jun 17, 2020 at 16:36

2 Answers 2

2
 var sumgas = 0; 
 var sumelectric = 0;
 var date = '2020-06-20';
 json['data']['label'].forEach(function(row,idx){
   try{
       row['Gas'].forEach(function(row,idx){
           if(new Date(row['due_date']).getTime() > new Date(date).getTime()) 
           {
               sumgas += parseInt(row['total_bill'])
           }
       })
      row['SumGas'] = sumgas
   }
   catch(e){

   }
   try{
       row['Electricity'].forEach(function(row,idx){
           if(new Date(row['due_date']).getTime() > new Date(date).getTime()) 
           {
               sumelectric += parseInt(row['total_bill'])
           }
       })
     row['sumelectric'] = sumelectric
   }
   catch(e){

   }
});

console.log(sumgas)
console.log(sumelectric)

you can use this code without anychange

Sign up to request clarification or add additional context in comments.

2 Comments

Hello.I fixed it.
Hello. I fixed it. Pls check it
1

In addition to @dauren's answer, here's an alternative way to solve the problem you posted:

json.data.label.
    reduce((results, currentServiceObject) => {
        let services = Object.keys(currentServiceObject);
        services.forEach(billedService => {
            currentServiceObject[billedService]
                .forEach(monthlyBill => {
                        let { total_bill, due_date } = monthlyBill;
                        let monthIndex = new Date(due_date).getMonth();
                        results[monthIndex] = 
                            results[monthIndex] ? 
                                Number.parseFloat(results[monthIndex]) + Number.parseFloat(total_bill) : 
                                Number.parseFloat(total_bill);
                })
            });
        return results;
    }, {})

You'll notice that iteration is a little bit more involved in this case, however, none of the properties or names of the bills (such as "Electricity") need to be known in advance, neither the dates. We just assume (or expect) that objects that represent bills such as "Electricity" conform to an object that is shaped by two properties: 'total_bill' and 'due_date' and that the former contains a string value that represents the billed amount, and the later contains a string representing a date.

The return value of the code above will be an object, in this particular case Object { 5: 217.8, 6: 182.63 } where 5 represents the 6th month in a given year and 6 represents the 7th month.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.