2

I have an array of objects and I am looking to sum each objects value. I have attempted to implement reduce() and forEach() from the following post to no avail.

How can I return the sum of each of the keys in the newProducts var?

$scope.products = [];
      var userId = firebase.auth().currentUser.uid;
      firebase.database().ref('accounts').orderByChild('userId').equalTo(userId).once('value').then(function(accounts) {
        if (accounts.exists()) {
          accounts.forEach(function(account) {
            $scope.accountId = account.key;
            $scope.productIds = account.val().products;
            if (!$scope.productIds) {
              //User has no products yet!
              Utils.hide();
            }
            //Fetch each products the user have given the productIds
            $scope.productIds.forEach(function(productId) {
              //Get the product.
              firebase.database().ref('products/' + productId).once('value', function(product) {

                //Create product object to be added to the productList.
                var newProducts = {
                  id: productId,
                  name: product.val().name,
                  shareCount: product.val().shareCount,
                  viewCount: product.val().viewCount
                };

                //Add product to productList.
                $scope.products.push(product);
                $scope.$apply();
                Utils.hide();

              });
            });
          });
        }
      });

Thanks in advance!

Community
  • 1
  • 1
MacD
  • 566
  • 3
  • 9
  • 27
  • You have `...once('value', function(product) {...` then `var product = {...}` which doesn't seem like a good idea as it's easily misunderstood. – RobG Feb 05 '17 at 01:37
  • edited for clarity.. thanks – MacD Feb 05 '17 at 01:43

0 Answers0