"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
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.
simple. JSONObject to merge two JSON objects in Java. We can merge two JSON objects using the putAll() method (inherited from interface java.
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.
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,
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With