sum inside the loop vue js
########### HTML ############
<div id="app">
<div v-for="report in reports">
<h2>{{ report.year }}</h2>
<table class="table table-striped">
<thead>
<tr>
<th>Month</th>
<th>Number of orders</th>
<th>Total revenue</th>
<th>Average order</th>
</tr>
</thead>
<tbody>
<tr v-for="value in report.values">
<td>{{ value.month }} {{ value.year }}</td>
<td>{{ value.orders }}</td>
<td>£{{ value.revenue }}</td>
<td>£{{ value.average }}</td>
</tr>
</tbody>
<tfoot v-if="reports">
<tr>
<td>Total {{report.year }}</td>
<td>{{ totalOrders(report.values) }}</td>
<td>£{{ totalRevenue(report.values) }}</td>
<td></td>
</tr>
</tfoot>
</table>
</div>
</div>
########### JS #############
const app = new Vue({
el: '#app',
data: {
reports: []
},
created() {
fetch('https://api.myjson.com/bins/16731e')
.then(response => response.json())
.then(json => {
this.reports = json.reports
});
},
methods: {
totalOrders: function (values) {
return values.reduce((acc, val) => {
return acc + parseInt(val.orders);
}, 0);
},
totalRevenue: function (values) {
return values.reduce((acc, val) => {
return acc + parseInt(val.revenue);
}, 0);
}
}
});
Working fiddle: https://jsfiddle.net/4js8L3p9/.