How can I calculate the total amount from an array?
I pass data to the child component as prop, and I am stuck here. When I console log prop, it returns a very complicated object . I tried this.values.reduce()
function but it does not work.
<template>
<tr v-for="value in values" >
<th scope="row">{{$index+1}}</th>
<td>{{value.name}}</td>
<td>-</td>
<td>${{value.total}}</td>
</tr>
<tr>
<th></th>
<td><strong>Total:{{total}}</strong></td>
<td>-</td>
<td>-</td>
</tr>
</template>
<script>
export default {
props: ['values'],
ready: function() {
}
}
</script>
In case anyone else is in the same situation as me I thought I'd add this answer. I needed to get the values from nested objects then push them to an array before reducing them:
This uses ES7
.entries
to loop through the object which looked like this:You can then display the total in your template with:
As you proposed, you could use the
Array#reduce
function. Starting from this example on SO, you could adapt it to your needs and only addvalue.total
to the sumtotal.To compute the total of all values, you can use
computed properties
, which will display as{{ total }}
in your template:Note: This will of course only work, if
value.total
is a unitless number (e.g.1
, not'1 USD'
). Otherwise you would need to strip the in the reduce function as well.