Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum value of two json object key?

"bills": [
    {
        "refNo": 17,
        "billDate": "1-apr-2016",
        "dueDate": "30-apr-2016",
        "pendingAmount": 4500,
        "overdueDays": 28
    },
    {
        "refNo": 20,
        "billDate": "15-apr-2016",
        "dueDate": "3-may-2016",
        "pendingAmount": 56550,
        "overdueDays": 15
    }
]

I want to sum "pendingAmount" field. It should be return like pendingAmount: 61050

like image 716
Avijit Dutta Avatar asked Jun 08 '17 12:06

Avijit Dutta


People also ask

How do I get key value pairs in JSON?

In order to get a key-value pair from a KiiObject, call the get() method of the KiiObject class. Specify the key for the value to get as the argument of the get() method. The value of the key at the first level of the JSON document hierarchy will be obtained.

How do you add two JSON objects together?

simple. JSONObject to merge two JSON objects in Java. We can merge two JSON objects using the putAll() method (inherited from interface java.

How do I count the number of keys in JSON?

To count the number key/value pairs in a JSON object we need to convert an array. And then we can easily count the number of element in the array which is same as the number key value pairs in the json object. Object.


2 Answers

You can use Array#map and then Array#reduce to flatten your object and then sum the result of the map :

bills.map(bill => bill.pendingAmount).reduce((acc, amount) => acc + amount);

here's a snippet :

var bills = [
          {
            "refNo": 17,
            "billDate": "1-apr-2016",
            "dueDate": "30-apr-2016",
            "pendingAmount": 4500,
            "overdueDays": 28
          },
          {
            "refNo": 20,
            "billDate": "15-apr-2016",
            "dueDate": "3-may-2016",
            "pendingAmount": 56550,
            "overdueDays": 15
          }
        ];
var res = bills.map(bill => bill.pendingAmount).reduce((acc, amount) => acc + amount);
console.log(res)

Hope it helps,

Best regards,

like image 115
boehm_s Avatar answered Oct 29 '22 22:10

boehm_s


The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

var bills = [
          {
            "refNo": 17,
            "billDate": "1-apr-2016",
            "dueDate": "30-apr-2016",
            "pendingAmount": 4500,
            "overdueDays": 28
          },
          {
            "refNo": 20,
            "billDate": "15-apr-2016",
            "dueDate": "3-may-2016",
            "pendingAmount": 56550,
            "overdueDays": 15
          }
        ];
        
        
      var result = bills.reduce(function(_this, val) {
          return _this + val.pendingAmount
      }, 0);

    console.log(result)
    //61050 answer
like image 5
Sujith S Avatar answered Oct 29 '22 22:10

Sujith S