Sum of values in Array returns NaN

1

I have an array of requests, plus one of them contains an additional value. I made the sum with $ watchCollection, plus it is returning NaN result. How do you add these values when the object does not have the additional value.

.controller('MyCtrl', function($scope) {

$scope.seuPedido = [
{nome: 'produto 1', valor: 10.00, quantidade: 3},
{nome: 'produto 2', valor: 20.00, quantidade: 1},
{nome: 'produto 3', valor: 30.50, quantidade: 1, adicional: 10}
];

$scope.$watchCollection('seuPedido',function() {
$scope.total = 0;
angular.forEach($scope.seuPedido, function(value, key) {
  $scope.total += value.quantidade * (value.valor + value.adicional);
  console.log($scope.total)
})
});

});

Follow the codepen: link

    
asked by anonymous 14.03.2016 / 19:02

2 answers

4

In your calculation function assume a default value for items that do not have the adicional property:

$scope.total += value.quantidade * (value.valor + (value.adicional || 0));
//                 Operador 'Coalesce': Valor, ou caso nulo zero --^
    
14.03.2016 / 19:39
0

Place the additional value element: 0 on products that have no additional value.

    
14.03.2016 / 19:08