2017-04-06 53 views
1

我有一個前端有一個訂單表。每個訂單可以交付,不交付或部分交付。我需要根據選擇哪個選項來計算總計(因此總計也被過濾),並且我確實找到了一個解決方案,但我知道我過於複雜,我並不是一個真正的AngularJS開發人員。AngularJS計算幾個相同對象的合計

function calculateTotals(){ 

    vm.sales.total_amount = {'_': 0, '_not': 0, '_part': 0, '_done': 0, 'n-p': 0}; 
    vm.sales.total_price = {'_': 0, '_not': 0, '_part': 0, '_done': 0, 'n-p': 0}; 
    vm.sales.order_total_price = {'_': 0, '_not': 0, '_part': 0, '_done': 0, 'n-p': 0}; 
    vm.sales.order_total_amount = {'_': 0, '_not': 0, '_part': 0, '_done': 0, 'n-p': 0}; 

    angular.forEach(vm.sales, function (sale) { 
     angular.forEach(vm.sales.total_amount, function(value, key){ 
      vm.sales.total_amount[key] += (sale.status == key) ? sale.total_amount * 1 : 0; 
      vm.sales.total_price[key] += (sale.status == key) ? sale.total_price * 1 : 0; 
      vm.sales.order_total_amount[key] += (sale.status == key) ? sale.order_total_amount * 1 : 0; 
      vm.sales.order_total_price[key] += (sale.status == key) ? sale.order_total_price * 1 : 0; 
     }); 
     vm.sales.total_amount['_'] += sale.total_amount * 1; 
     vm.sales.total_price['_'] += sale.total_price * 1; 
     vm.sales.order_total_amount['_'] += sale.order_total_amount * 1; 
     vm.sales.order_total_price['_'] += sale.order_total_price * 1; 
    }); 

    vm.sales.total_amount['_'] = vm.sales.total_amount['_'] - vm.sales.total_amount['n-p']; 
    vm.sales.total_price['_'] = vm.sales.total_price['_'] - vm.sales.total_price['n-p']; 
    vm.sales.order_total_amount['_'] = vm.sales.order_total_amount['_'] - vm.sales.order_total_amount['n-p']; 
    vm.sales.order_total_price['_'] = vm.sales.order_total_price['_'] - vm.sales.order_total_price['n-p']; 
} 

有4個變量我需要在前面,總量和總價格(許多交付的總和,從Laravel後端未來總結),訂單總價格和訂單總量(從Laravel後端取)。

我該如何簡化?

編輯感謝stej4n我已經走到這...雖然我仍然覺得它可以去簡單

function calculateTotals() { 

    var properties = ['total_amount', 'total_price', 'order_total_amount', 'order_total_price']; 
    var keys = ['_', '_not', '_part', '_done', 'n-p']; 

    angular.forEach(properties, function (prop) { 
     vm.sales[prop] = {'_': 0, '_not': 0, '_part': 0, '_done': 0, 'n-p': 0}; 
    }); 

    angular.forEach(vm.sales, function (sale) { 
     angular.forEach(properties, function (prop) { 
      vm.sales[prop]['_'] += sale[prop] * 1; 
      angular.forEach(keys, function (key) { 
       vm.sales[prop][key] += (sale.status == key) ? sale[prop] * 1 : 0; 
      }); 
     }); 
    }); 

    angular.forEach(properties, function (prop) { 
     vm.sales[prop]['_'] -= vm.sales[prop]['n-p']; 
    }); 
} 

回答

1

4個最後一行已經可以簡化這種方式:

angular.forEach(['total_amount', 'total_price', 'order_total_amount'], function(prop) { 
    vm.sales[prop] -= vm.sales[prop]['n-p']; 
}); 

(sale.status == key)從哪裏來? status屬性不存在於vm.sales的任何對象中?

附加的優化:刪除所有* 1,它不會改變任何東西^^

+0

vm.sales是從後端獲取的集合。每個銷售有一個狀態 – Norgul

+0

我認爲你可以安全地刪除每個'* 1' –