2016-11-10 58 views
1

我必须得到unit_price数字的总和。我怎样才能做到这一点?从数组中取得对象属性的总和

数组是这样的:

$scope.items = [ 
    { 
     id: '1', 
     name: 'Phone', 
     quantity: '1', 
     unit_price: '200' 
    }, 
    { 
     id: '2', 
     name: 'IPhone', 
     quantity: '1', 
     unit_price: '240' 
    } 
]; 
+0

请发表[MCVE]和一些努力 – mplungjan

回答

8

reduce数组:

var total = $scope.items.reduce(function(x,y) { return x + parseInt(y.unit_price) }, 0); 
+0

这是解决方案 :) –

1

试试这个:

var sum = 0; 
angular.forEach($scope.items, function(value, key){ 
    sum = sum + value.unit_price; 
});