Sum of values in Array returns Nan

Asked

Viewed 673 times

1

I have an array of orders, 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)
})
});

});

Follows the codepen: http://codepen.io/alexandre_developer/pen/bpwzzB?editors=0011

  • Would there be no rule for additional value? How should the calculation be if it does not exist?

  • Wouldn’t it be cool if you put a Ternario before making the sum, something like var valorAdicional = value.adicional == undefined? 0 : value.adicional;$scope.total += value.quantidade * (value.valor + valorAdicional);

2 answers

4


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

$scope.total += value.quantidade * (value.valor + (value.adicional || 0));
//                 Operador 'Coalesce': Valor, ou caso nulo zero --^
  • It worked here @lbotinelly. Thanks for the tip. I solved not that, but other problems I was having here. Thanks for the force!

  • @Alexandrescrideli I’m glad it worked - and it’s always a pleasure to help. =)

0

Add the additional value:0 element to products that have no additional value.

  • Plus this array I did is an example. The q array I need to enter code, is a push, and some objects do not return the additional value

  • without problems, once you receive the itere Collection it putting the additional value=0 in each element. for (var i=0; i<$Scope.seuPedido.length;i++) { $Scope.your request[i]. additional=0; }

  • Only put an if before assigning 0 to only those with the attribute as Undefined: if(! $Scope.seurequest[i]. additional)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.