Sum all of the property values in an array using Vue.js

I'm currently developing a small app and have an array of objects with two properties each: 'label' and 'value'. I want to calculate the total value by adding up all the values in the 'value' property.

Vue/JS

data() {

totalRequest: 0,

   donutData: [
        { label: 'Pending requests', value: 20 },
        { label: 'Accepted requests', value: 25 },
        { label: 'Rejected requests', value: 10 }
    ],

},

created() {
        this.totalRequest = //Functionality needed to sum up all values in the 'value' property (total should be 55)
}

HTML

total value {{ totalRequest }}

In this example, there are 3 objects with a total value of 55 (the sum of all 3 'value' properties). How can I achieve this? Thank you in advance.

Answer by dashton, adapted for vue

created() {
        this.totalRequest = this.donutData.reduce((acc, item) => acc + item.value, 0);
}

Answer №1

Here is a solution that should do the trick:

let total = donutData.reduce((accumulator, currentItem) => accumulator + currentItem.value, 0);

Answer №2

This solution does not involve Vue at all, but rather a JavaScript approach. There are various ways to achieve the desired result, with one simple method being to use a forEach loop:

ES4:

for(i in donutData) { this.totalRequest += donutData[i].value; }

If your goal is to display {{ totalRequest }}, you may want to consider utilizing computed properties:

https://v2.vuejs.org/v2/guide/computed.html

Computed properties in Vue allow for dynamic data integration into views. For example, you could follow dashton's response by implementing the following code:

HTML

Total value: {{ totalRequest }}

Vue/JS

data() {
   donutData: [
        { label: 'Open Requests', value: 20 },
        { label: 'Accepted Requests', value: 25 },
        { label: 'Rejected Requests', value: 10 }
    ],

},
computed: {
    totalRequest() {
      return this.donutData.reduce((acc, item) => acc + item.value, 0);
    }
}

Answer №3

While all the responses provided appear to be correct, if you continue to encounter issues and have the specific code on hand, it is crucial to ensure that your data (the values you are summing) are in integer format.

For example, if the value is set as "12" and "34", the result will be "1234" instead of 46.

To convert to an integer, use parseInt() method:

array.reduce((acc, item) => acc +parseInt( item.value), 0)

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

struggling to determine the connection status between tables (Many-to-many or one-to-one)

Seeking assistance: I am working with two tables (member, event) where each member attends multiple events and each event has multiple attendees. Do these relationships represent a many-to-many or one-to-one relationship? ...

Are there any methods to determine the way in which a user has absorbed the content of a post

This particular question sets itself apart from the one found here, as it aims to detect various user behaviors beyond just browser activity. Specifically, I am interested in identifying behaviors such as: Rapidly skimming through an article from start ...

How to fetch select element within a table by using jQuery

I encountered a situation where I have a table element with a select element inside its td. The id of the table (in this example, it is "table1") could potentially change. So my query is, how can I retrieve the selected option using the table ID in JQuer ...

MongoSessionEndedError: Session expired and cannot be utilized

I have been working on creating new documents from existing ones within a collection in my database. Specifically, I am flattening a field from the original document during this process. Initially, everything ran smoothly using mongosh but now that I need ...

Having trouble with my loop using Jquery's $.get method

Having an issue with Jquery mobile / JavaScript I'm struggling to properly loop through the different values of data in my "get" function, where it should be sending ...cmd=PC&data=06464ff ...cmd=PC&data=16464ff ...cmd=PC&data=26464ff ...

Tips for Comparing and Extracting Values from Two Arrays of Objects

There are two sets of objects that I need to work with: First set of objects ----> [{locationId: 1, locationName: "Bangalore"}, {locationId: 2, locationName: "Mumbai"}] Second set of objects -----> [{baseId: 1, baseUnit: "abc"}, {baseId: 2, b ...

Steps for choosing a row from a dynamic table when clicking the mouse

Is there a way to retrieve a row's value upon mouse click or by checking the checkbox in the provided HTML table? Below is the JavaScript code for fetching values from a table using Spry, sourced from an XML file: var ds1 = new Spry.Data.XMLDataSet( ...

Ajax removes the selection from the hyperlink under the mouse cursor

Currently, my webpage is set up to constantly refresh a div using an Ajax request every second. Within this div are hyperlinks. Unfortunately, when users hover over one of the hyperlinks and pause for a moment without moving their cursor, the "hover" pseu ...

Placing options and a clickable element within a collapsible navigation bar

Within my angular project, there are 4 input fields where users need to enter information, along with a button labeled Set All which will populate them. https://i.sstatic.net/1GGh1.png I am wondering how I can organize these input fields and the button i ...

What is the name of the JavaScript code editor that includes line numbering for plain text?

Looking to incorporate a text area with line numbering features. I experimented with EditArea, but encountered difficulties when working with text files. While syntax highlighting for various programming languages would be a nice touch, my primary focus ...

Aligning the second heading alongside pictures and a lightbox

My issue is that I am struggling to center the "See More" link directly under each title link. Currently, it is pushed to the right and I can't seem to find a solution. Any help with this problem would be greatly appreciated. I attempted using display ...

Copying data with CUDA involves transferring an array of pointers, where each pointer references its own array

I am facing an issue with transferring pointers from an array on the host to the device. The goal is to create an array of pointers on the host, where each pointer points to an array of size 4. However, when attempting to copy a pointer to the device, th ...

Accessing each element within a Next.js application through a personalized hook during page load

Within my Next.js application, I have implemented a React hook that retrieves the currently authenticated user and stores it in global state. I am looking to execute this hook once on page load while making it accessible to every component within the app. ...

Utilize Vuex's $store.getters within a component's method() function

I am facing a challenge in dynamically populating a dropdown list using Vuex and Vuetify for a search box. My issue lies in the fact that I am unable to access the $store within the method() function, only through computed() of course. Below are my getter ...

BX-Slider allows for the insertion of Prev and Next Arrows in both the Main Div and Inner Divs

I am facing an issue with positioning inner boxes (divs) to the left or right of each slide while adding some text. Although styling them is easy, the problem arises when the Previous and Next arrows appear inside the secondary/inner div, as shown in the a ...

How to Handle an Empty Route with a Trailing Slash in Backbone Routing?

While I am aware of the potential SEO issues that come with duplicate content, my project is not currently focused on that aspect. Looking at my backbone router configuration, here it is: routes: { "": "startOrder", "order/:orderNumber/:stepName" ...

What is the best way to automatically place the cursor in a text box when a webpage is loaded using JavaScript?

Just starting out in web development and looking to enhance my skills. I am trying to find a way to automatically place the cursor in a specific text box on a website when the page loads. Currently, I am experimenting with the Greasemonkey add-on for this ...

Ensure that the landing image remains in place and covered as I continue scrolling

Can someone help me figure out how to adjust my landing page so that as I scroll, the content covers the background image? I'm looking for a similar effect to what's seen on this website: ...

Manipulating the position of particles in a THREE.ParticleSystem using Three.js

I am faced with the challenge of manipulating multiple particle systems, each containing approximately 20,000 vertices. My goal is to individually move each particle within these systems to a new Vector3 location that corresponds to a specific shape I have ...

The Angular data model fails to update when the URL is modified

SOLUTION: var deferred2 = $q.defer(); It is important to place this inside the method _getSpecificPerson(), as visiting other Person promises in already resolved. This ensures that a new deferred object is created each time. Imagine having a list of perso ...