[Vuejs]-Compute data from an array with VueJS

2๐Ÿ‘

โœ…

You can just reduce the sum of votes in the then function

axios.get("http://example.com/votes.json")
    .then(response => {
         this.results = response.data;
         this.resultsVotes = this.results.reduce((sum, curr) => sum + curr.votes, 0);
    });

1๐Ÿ‘

If the question is how to compute resultVotes, computed value is recommended:

const vm = new Vue({
  el: '#app',
  data: {
    results: []
  },
  computed: {
    resultVotes () {
      return this.results.reduce((sum, val) => sum + val.votes, 0);
    }
  },
  mounted() {
    axios.get("http://example.com/votes.json")
    .then(response => {this.results = response.data})
  },
});

Leave a comment