Discover how to sum all the elements at a specific index within a JavaScript array using Vue.js

I am working on a project where I have created an array of products to display using VueJS. Each time a user selects a product, it is added to a list and the "Count" value increments. The "Total Price" for each product is calculated by multiplying the "Count" with the "Price". However, I now need to find a way to add up all the "Total Prices" of all products to show the user the overall Total Price. Should I use a "For Loop" for this task?

Persons: [
    {Name: 'Ali', Family: 'Bahaari', Age: 20, Count: 0, Price: 200},
    {Name: 'Akbar', Family: 'Jahan', Age: 30, Count: 0, Price: 2500},
    {Name: 'Amir', Family: 'Pirozi', Age: 40, Count: 0, Price: 500},
    {Name: 'Reza', Family: 'Khosravi', Age: 50, Count: 0, Price: 100}
]

<tr v-for="Active in Activated">
    <td>{{ Active.Name }}</td>
    <td>{{ Active.Family }}</td>
    <td>{{ Active.Age }}</td>
    <td>{{ Active.Count }}</td>
    <td>{{ Active.Price }}</td>
    <td>{{ Active.Count * Active.Price }}</td>
</tr>

Answer №1

Create a computed property to calculate the total sum:

computed: {
    grandTotal() {
        return this.OrderItems.reduce((sum, item) => sum + item.Quantity * item.Price, 0);
    }
}

Now you can easily display it in the template: {{ grandTotal }}

Answer №2

Below is an illustration

http://jsbin.com/xumugemiza/edit?html,js,output

const application = new Vue({

  el: '#application',

  data: {
    people: [
    {Name: 'Ali', Family: 'Bahaari', Age: 20, Count: 0, price: 200},
    {Name: 'Akbar', Family: 'Jahan', Age: 30, Count: 0, price: 2500},
    {Name: 'Amir', Family: 'Pirozi', Age: 40, Count: 0, price: 500},
    {Name: 'Reza', Family: 'Khosravi', Age: 50, Count: 0, price: 100}
    ]
  },

  computed: {
     sum() {
       let overall = 0
       this.people.forEach(person => overall += person.price )
       return overall
     }
  }

})

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

Can Node.js fetch a PHP file using AJAX?

The Challenge: Greetings, I am facing an issue with my website that features a game created using node.js, gulp, and socket.io. The problem arises when I attempt to call a php file from node.js. While the file returns a success message (echo in the file) ...

Managing data from two tables in Node.js with ejs

I have a question regarding my node.js project that I need help with. As a beginner in this field, I believe the answer may be simpler than anticipated. In my code file named index.js, I found the following snippet after referring to some online documenta ...

Ensuring proper execution of the next callback function in an Express get request

I am currently running an express server on nodejs with a specific file structure that I need to convert into a list of links. Included below are my recursive functions for dealing with the file structure. Here are the file structure functions: function ...

Implementing a Modal Based on Valid Input

I'm currently developing a journal book app using Flask and Bootstrap 5. One of the features I'm working on is a deletion feature, where users can input the number of records they want to delete. I want this feature to display a confirmation moda ...

Ensuring key code functionality in Vue.js for a smart TV application

Recently, I have started exploring Vue.js and would like to implement remote key functionality in my Vue.js project. Can anyone provide guidance on how I can develop an app for smart TVs? ...

Combining Vue-Test-Utils with TypeScript typings for wrapper.vm

So, I ran into an interesting situation. Has anyone ever worked with typescript + vue-test-utils and attempted to change a value for testing purposes like this: wrapper.vm.aCoolRefValueToManipulate = 'something much cooler'? I gave it a shot, a ...

React Tetris game always returns false in its function

Within my react project, I am working with a 2D array containing numbers. I have implemented a function called collisionCheck that iterates through the array to check for specific values. My goal is for this function to return true and exit when it encou ...

Exploring Vue JS and Quasar: Unraveling the Mystery of @functionname within router-view

Just starting out with vue and quasar. This piece of code is in my vue file, but I'm not quite sure what it does. <router-view v-if="some_object" :abc="abc" :xyz="abc_xyz" :title="title" @updated="getABC" @refreshABC="getABC"/> As far as I kno ...

Easily integrating a JavaScript file into an HTML document when utilizing a NodeJS Express server

Currently in the process of developing a chat application, utilizing the Express server with NodeJS and AngularJS for client-side management. Encountering an issue when attempting to include /js/code.js in my html, as it cannot be found due to not being p ...

Error 404: Node.js and Express encountering issues with POST request to '/webhook' endpoint

https://i.sstatic.net/CTDCv.pnghttps://i.sstatic.net/KjPeC.pngI've encountered a peculiar issue where I keep receiving a 404 error specifically when sending a post request to '/webhook'. This error is persistent even though the rest of my po ...

Step-by-step guide on how to showcase elements within v-for by clicking on them

In my data array, only the first element is visible by default. Clicking on either the YES or NO button will display the element with the corresponding id of yes_section or no_section (depending on which button was clicked). For instance, if we click on ...

Converting an rrule date value from an array to a customized string format

Here is an array that I am working with: [{ evening_feeding: false evening_feeding_time: "19:00" feeding_frequency_rule: **"FREQ=DAILY;INTERVAL=2"** id: 890 morning_feeding: true morning_feeding_time: "04:00 ...

Fetching an item from Local Storage in Angular 8

In my local storage, I have some data stored in a unique format. When I try to retrieve the data using localStorage.getItem('id');, it returns undefined. The issue lies in the way the data is stored within localStorage - it's structured as a ...

Performing a conditional query on a Many-to-Many relationship in TypeORM

Operating under a many-to-many relationship between Category and Product entities In need of filtering products based on category ID Attempted to implement the following code after referring to some examples, but encountered difficulties in making it fun ...

Unlocking the nested v-for in Vuejs to access id and submit using axios

I am currently working on developing an application that utilizes a typeorm backend and a Vue.js frontend. This app is designed to collect customer data through surveys. For this purpose, I retrieve data from my backend using an axios get request, and I i ...

Display an icon before an active v-list-item in Vuetify 3's v-list

I need help figuring out how to add an icon to a v-list-item only if it is active. <v-list class="px-15 pt-5" border density="compact"> <v-list-item v-for="(item,i) in items"> <!-- Need assistance putting ...

Deleting a string by utilizing the Ternary operator in JavaScript

How do I remove the [object Object] from my output shown in the console? I'm looking to print the output without the [Object Object]. Is it possible to achieve this using a ternary operation? data:[object Object] text:Data is supplied by Government ...

What is the best way to manage the cumulative index within two nested ng-repeats?

Within the scope of a directive, I am working with two ng-repeats. This directive is responsible for generating a table, and each table cell's data comes from a separate data source. This data source requires the cumulative index of the two repeaters. ...

Issues have been observed with the functionality of the Node.js EventEmitter when attempting to

Here's the issue: I have a class called save.js that inherits from EventEmitter. Here's how it looks: var util = require('util'); var EventEmitter = require('events').EventEmitter; var save = function(pdf){ var ...

Why is the radio button not chosen in the ns-popover popup? The radio button is only selected in the popup of the last column

In my Angular controller, I am trying to set the radio model but it is only appearing in the last column popup of the table. The ns-popover is displayed when clicking on a table column. Here is the Angular Code: var app = angular.module('app', ...