I am working on a small app and I have a array with objects and within the objects 2 property's, one called 'label' and one 'value'. What I would like is to add up all values of the property 'value', So that I have one total value.
Vue/JS
data() {
totalRequest: 0,
donutData: [
{ label: 'Openstaande verzoeken', value: 20 },
{ label: 'Geaccepteerde verzoeken', value: 25 },
{ label: 'Afgewezen verzoeken', value: 10 }
],
},
created() {
this.totalRequest = //here goes the function to add up all value's of the property 'value' (total value should be 55)
}
HTML
total value {{ totalRequest }}
So in this example I have 3 objects with a total value of 55 (all 3 property 'value'). How can I achieve this? Thanks in advance.
Answer by dashton, reproduced for vue
created() {
this.totalRequest = this.donutData.reduce((acc, item) => acc + item.value, 0);
}
This will work:
var sum = donutData.reduce((acc, item) => acc + item.value, 0);
This has nothing to do with vue, seems like a javascript question, there's tons of way of doing this, the simpler would be just do a forEach:
es4:
for(i in donutData) { this.totalRequest += donutData[i].value; }
BUT as you asked how to show {{ totalRequest }} you might want to look at computed properties:
https://v2.vuejs.org/v2/guide/computed.html
Which is a way vue has to dynamically set data in views, so you could take dashton's answer and do:
HTML
total value {{ totalRequest }}
Vue/js
data() {
donutData: [
{ label: 'Openstaande verzoeken', value: 20 },
{ label: 'Geaccepteerde verzoeken', value: 25 },
{ label: 'Afgewezen verzoeken', value: 10 }
],
},
computed: {
totalRequest() {
return this.donutData.reduce((acc, item) => acc + item.value, 0);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With