Calculating information from an array using VueJS

I am eager to use VueJS to process data from my JSON source

Here is an example of the data structure:

JSON obtained via API

[
    {
        "id": 4,
        "votes": 0
    },
    {
        "id": 3,
        "votes": 1
    },
]

In order to fetch and display this data, I have implemented the following VueJS script:

app.js

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

My next task is to create a Vue variable that will show the total number of votes in my index.html file.

index.html

<div v-for="result in results">
    <p>Votes {{ result.votes }}.</p>
    <p>Id : {{ result.id }}</p>
</div>
<div>
    <p>Total Votes: {{ resultsVotes }}</p>
</div>

Answer №1

The sum of votes can be easily calculated by using the reduce method within the then function.

axios.get("http://mywebsite.com/votes.json")
    .then(response => {
         this.data = response.data;
         this.totalVotes = this.data.reduce((sum, current) => sum + current.votes, 0);
    });

Answer №2

If you're wondering how to calculate resultVotes, it is suggested to use the computed property:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Employing the 'this' keyword for iterating over a jQuery selector

Having an issue with a jQuery code that logs the values of input fields on button click: Tried using forEach method on inputs but getting an error saying it's not a function. Why is this happening? $("#submit").click(e => { e.preventDefault(); ...

IE is failing to trigger jAlert function

When I validate a text box by pressing the enter key on my keyboard, the validation works fine but the JAlert doesn't show up. However, when I call the same function on a button click, the alert shows in IE. I am quite confused by this behavior and wo ...

How to select an unwrapped element using the v-popover component

The v-popover component is commonly used by wrapping an element inside of it, like so: <v-popover offset="0" placement="right"> <span>My awesome span</span> <template slot="popover">My awesome popov ...

When making an AJAX request to an ASP.NET web method, strange characters are appended to the end of the response text. This issue seems

I need assistance with the following code: $.ajax({ type: 'POST', contentType: 'application/json; charset=utf-8', url: location, data: JSON.stringify(ajaxData), dataType: 'xml', success: ca ...

Protractor troubleshooting: Issues preventing execution of protractor tests

My tests suddenly started throwing an error. Everything was working fine before this. Any advice on how to fix it? Here is my Config file: exports.config = { seleniumAddress: 'http://localhost:4444/wd/hub', allScriptsTimeout: 20000, baseU ...

What is the best way to use node.js to send a .json file via HTTP POST request?

As a beginner in these concepts, I seek guidance on how to create a script for making an HTTP POST request that sends a .json file containing an array of jsons. My resource is an npm module available at: https://github.com/request/request, along with a tut ...

Building a time series collection in MongoDB with Node.js

Are there any npm packages available for creating mongodb time series collections using node.js? I did not find any documentation related to this in the mongoose npm package. ...

Shifting the pagination outside of the slider in ReactJS and SwiperJS seems to be tricky. Despite trying to adjust the margins and padding, the pagination

I've been struggling with this issue for a while now. I need to move the pagination outside of the slider, but using padding or margin doesn't seem to work. It always remains inside the slider, and if I try to position it outside, it gets hidden. ...

The carousel feature results in the screen jumping to the top of the page when switching slides

View GitHub for Minimum Reproducible Example (Images are not displayed in this example, but it does not affect the issue being discussed) Challenge: The screen automatically scrolls to the top of the page every time the slide index changes. This occurs w ...

Filtering out section boxes does not eliminate empty spaces

Link to Fiddle I've run into a bit of a roadblock while trying to filter my section box for a project I'm currently working on. The issue I'm facing is that instead of collapsing the first section box to display only the filtered options, i ...

What is causing the malfunction of Vue's method?

I'm attempting to create a Vue method, and I've encountered an issue where 'clickA' does not function, but 'clickB' does. Can someone explain why this is happening? It's important that the solution allows the throttle fu ...

Is it possible to implement the same technique across various child controllers in AngularJS?

I am trying to execute a function in a specific child controller. The function has the same name across all child controllers. My question is how can I call this function from a particular controller? Parent Controller: app.controller("parentctrl",functi ...

A guide on extracting the parent element from a JSON object with Vue.js

I'm currently dealing with flattened JSON data and encountering difficulties in accessing certain parts of it. My goal is to utilize the accessible elements to retrieve their parent elements for display. I am able to determine the count of arrays with ...

Error encountered when attempting to serialize an object of type QueryResponse in Python 3.9 fastAPI with Pinecone that is not JSON serial

Upon receiving the API response from pinecone at results = {'matches': [{'id': 'yral5m', 'metadata': {'subreddit': '2qkq6', 'text': 'Black ...

Looking for a solution to the error "Nuxt.js is unable to locate the module '@vue/composition-api'." How can I fix this issue

While working on Nuxt.js development, I encounter an issue where the module '@ vue / composition-api' cannot be found. Why does this error occur? ...

Tips for exporting data to a JSON file using the Google Play Scraper in NodeJS

Recently, I've been exploring the Google Play Scraper and I'm in need of a complete list of all appIds using NodeJS. The issue I'm facing is that it only outputs to console.log. What I really require is to save this output to JSON and then c ...

Error: Required prop type check failed: The `children` prop in `InputAdornment` component is mandatory, but it is currently undefined

Whenever I execute my React.js front-end, I encounter this warning: index.js:1446 Warning: Failed prop type: The prop `children` is marked as required in `InputAdornment`, but its value is `undefined`. in InputAdornment (created by WithStyles(InputAdo ...

In configuring the print settings, I specified margins to ensure proper formatting. However, I noticed that the margin adjustment only applies to the first page. I need

I have a method that retrieves margin top value from the backend. It works perfectly on the first page of print, but on the second page, the margin top space is missing. initializePrintingSettings() { this.printService.fetchPrintSettings().subscribe(respon ...

Is it possible for data passed through props on Vue.js router-view to be visible in browser developer tools?

I have passed several props to the router-view component in this manner: <router-view :zipchange="zipchange" :accountitems="accountitems" :accountloaded="accountloaded" :profilepic="profilepic" /> Upon inspecting an element in the browser's de ...

PHP Unleashed: Unraveling the Mysteries

What is the Best Way to Extract Data from This Array? I Need to display the First Object of My Array, Specifically the id field in the 3rd Row. <?php $con=mysqli_connect("localhost","root","","arrayy"); // Check connection if (mysqli_conne ...