如何求和两个json对象键的值?

Avi*_*tta 4 javascript json

"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
          }
        ]
Run Code Online (Sandbox Code Playgroud)

我想对“pendingAmount”字段求和。它应该像pendingAmount一样返回:61050

boe*_*m_s 6

您可以使用Array#map然后Array#reduce将对象展平,然后对地图的结果求和:

bills.map(bill => bill.pendingAmount).reduce((acc, bill) => bill + acc);
Run Code Online (Sandbox Code Playgroud)

这是一个片段:

bills.map(bill => bill.pendingAmount).reduce((acc, bill) => bill + acc);
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你,

此致,


小智 5

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
Run Code Online (Sandbox Code Playgroud)