[Vuejs]-How to calculate the total in vue component ? Vue.JS 2

2👍

Since, TypeError: this.$store.state.transaction.list.reduce is not a function is an error marked in Frank’s answer I presume this.$store.state.transaction.list is not an Array but an object as v-for iterates through both.

total: function() { 
  var list = this.$store.state.transaction.list 
  var sum = 0 
  for(var listProps in list) { 
    list[listProps].products.forEach(function (product) { 
    sum += product.pivot.quantity * product.pivot.price 
    }) 
  } 
  return sum; 
}

0👍

Use another computed property

<script>
    export default {
        ...
        computed: {
            list: function() {
                return this.$store.state.transaction.list
            },
            total: function() {
                return this.$store.state.transaction.list.reduce(function(sum, item) {
                    sum += item.products.reduce(function(tmp, product) { tmp += product.quantity * product.price; return tmp; }, 0);
                    return sum;
                }, 0);
            }
            ...
        }
    }
</script>

Use a nested Array.reduce to get the total of your structure where the list has many items and an item has many products

👤Frnak

Leave a comment