Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

i'm trying to sum up a couple of properties in an object. I'm using a VueJS filter, in combination with the ES5 reduce function to add up the numbers to get a total.

Well, it's not working at this moment. Somebody care to help me out?

new Vue({
  el: '.app',
  data: {
    products: [{
      "pid": "37",
      "pname": "Reprehenderit",
      "price": "4.29",
      "amount": "1"
    }, {
      "pid": "45",
      "pname": "Sit",
      "price": "1.00",
      "amount": "4"
    }, {
      "pid": "67",
      "pname": "Omnis",
      "price": "7.00",
      "amount": "2"
    }],
  }
});

Vue.filter('subtotal', function (list, key1, key2) {
    return list.reduce(function(total, item) {
        return total + item.key1 * item.key2
    }, 0)
})
<script src="http://cdnjs.cloudflare.com/ajax/libs/vue/1.0.11/vue.min.js"></script>

<div class="app">
  
  Product example: {{ products[0].pname }}
  
  <br><br>
  
  Total: {{ products | subtotal 'price' 'amount' }}

</div>

share|improve this question
up vote 1 down vote accepted

Looks like your event handler is being initialized after the vue is already constructed. If your events aren't attached when they're called they'll be ignored.

Also, you can't reference your object properties like that product.variable you'll need to use product[variable]

Vue.filter('subtotal', function (list, key1, key2) {
    return list.reduce(function(total, item) {
        return total + item[key1] * item[key2]
    }, 0)
})

new Vue({
  el: '.app',
  data: {
    products: [{
      "pid": "37",
      "pname": "Reprehenderit",
      "price": "4.29",
      "amount": "1"
    }, {
      "pid": "45",
      "pname": "Sit",
      "price": "1.00",
      "amount": "4"
    }, {
      "pid": "67",
      "pname": "Omnis",
      "price": "7.00",
      "amount": "2"
    }],
  }
});
<script src="http://cdnjs.cloudflare.com/ajax/libs/vue/1.0.11/vue.min.js"></script>

<div class="app">
  
  Product example: {{ products[0].pname }}
  
  <br><br>
  
  Total: {{ products | subtotal 'price' 'amount' }}

</div>

share|improve this answer
    
Thanks! A complete and very clear answer :) Didn't know I had to init the filter first... – Milkmannetje Dec 14 '15 at 21:46

You could get the value of key like this:

return total + item[key1] * item[key2]

Also, you should set the filter before the vue instance.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.