"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
}
]
我要总结" pendingAmount"领域。 它应该像pendingAmount:61050一样返回
答案 0 :(得分:2)
您可以使用Array#map
然后使用Array#reduce
展平您的对象,然后对地图的结果求和:
bills.map(bill => bill.pendingAmount).reduce((acc, bill) => bill + acc);
这是一个片段:
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, bill) => bill + acc);
console.log(res)
希望它有所帮助,
致以最诚挚的问候,
答案 1 :(得分:0)
您可以使用以下代码段:
var sum = JSON.parse(bills).reduce(function(acc, val){
return acc.pendingAmount + val.pendingAmount;
}, {pendingAmount: 0});
它在解析的JSON上使用array.prototype.reduce()函数。 reduce的第二个参数是传递给reduce函数的初始值
答案 2 :(得分:0)
使用此:
let sum, billsPOJO;
billsPOJO = YOURJSON.bills;
sum = 0;
for (let i = 0; billsPOJO.length; i++) {
sum += billsPOJO[i].pendingAmount;
}
答案 3 :(得分:0)
带有一些ES2015解构的单线:
json.bills.reduce(({pendingAmount: a}, {pendingAmount: b})=> a+b)
答案 4 :(得分:0)
reduce()方法对累加器和数组中的每个元素(从左到右)应用一个函数,将其减少为单个值。
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