Vue.js: Performing calculations on object data within an array

I've experimented with various methods, but I haven't been able to achieve the desired outcome. My goal is to calculate the total sum of product answers from each array, yet I'm only able to do so for the first array. You can find my complete code on codepen by visiting the following link:

https://codepen.io/Thinker95/pen/bGbOrJb

Here's a snippet of my code:

Calculate(){
  this.fights[0].consumption = this.fights[0].rating*this.fights[0].quantity*this.fights[0].operation;
  this.answer = this.fights[0].consumption;

Answer №1

By accessing this.fights[0], you are only considering the first fight.

To calculate consumption for each fight and update this.answer, you should iterate over the entire fights array.

new Vue({
  el: "#app",
  data(){
    return {
      fights: [
        { device:'Laptop', rating:1000, quantity: 2, operation: 4, consumption: ''},
        { device:'Television', rating:900, quantity: 4, operation: 6, consumption: ''},
      ],
      answer: 0
    }
  },
  methods: {
    Calculate(){
      this.answer = 0
      this.fights.forEach(fight => {
        fight.consumption =  fight.rating * fight.quantity * fight.operation
        this.answer += fight.consumption
      })
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<div id="app">
  <div v-for="fight in fights">
    <h3>{{ fight.device }}</h3>
    <p>Rating: {{ fight.rating }}</p>
    <p>Quantity: {{ fight.quantity }}</p>
    <p>Operation: {{ fight.operation }}</p>
    <p>Consumption: {{ fight.consumption }}</p>
    <hr>
  </div>
  <button @click="Calculate">calculate</button>
  {{ answer }}
</div>

Answer №2

Make sure to run a loop through each element in the array.

Include this code snippet within your calculation function

this.fights.forEach((fight)=>{
  this.fight.consumption = this.fight.rating*this.fight.quantity*this.fight.operation;
  this.answer += this.fight.consumption
})

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

Arrays behaving badly

Take a look at this code: # Uncommenting the commented line below: # a = Array.new(3, Array.new(3)) a = [[nil,nil,nil],[nil,nil,nil]] a[0][0] = 1 a.each {|line| p line} When uncommented, the code produces this output: [1, nil, nil] [1, nil, nil] [1, nil ...

What steps should be taken in VUEjs if the API response is null?

There's a method in my code that retrieves a token from an API: let { Token } = await API.getToken({ postId: postId }) if(){} Whenever the token is null, I receive a warning in the console saying "Cannot read property 'Token' ...

Tips for sorting a nested array structure in JavaScript

Hello, I am facing a challenge with an array containing multiple values. My goal is to extract the indices related to my search bar. To put it simply, I need to find the index for the name "Name2" by examining the first value of each index in the array. C ...

Is it possible to create a typeguard for a complex combinatory type while retaining the existing type information?

Is there a method to create a TypeScript typeguard for a complex combinatory type that includes multiple "and" and "or" statements to check for the presence of one of the "or" types? For example: interface Type1 { cat: string } interface Type2 { d ...

Guide to crafting a reply using nestjs exception filters with nestfastify

I'm facing a challenge with writing custom HTTP responses from NestJS exception filters. Currently, I am using the Nest Fastify framework instead of Express. I have created custom exception filters to handle UserNotFoundException in the following mann ...

AngularJS - Issue with scope variable not reflecting changes in the view

I'm currently working with an AngularJS controller called HomeCtrl which is responsible for loading data from HTTP if it detects that there is existing data in LocalStorage. This detection process takes place when the controller is first accessed. v ...

Discover the shared word frequencies between two string variables

Let's consider having two strings that look something like this var tester = "hello I have to ask you a doubt"; var case = "hello better explain me the doubt"; In this scenario, both strings contain common words such as hello and doubt. Let's ...

Retrieve model from stored value

Many tutorials suggest using the JSONLoader when loading a Three.js model into a scene: var loader = new THREE.JSONLoader(); var createMesh = function(geometry) { var zmesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial() ); zmesh.position. ...

Angular 2 endless iframe loading issue

I'm working on setting up a simple iframe in an Angular 2 project. Check out the code here When I tried using a raw URL in the iframe src, I encountered an error saying unsafe value used in a resource URL context <!-- 1) Error : unsafe value use ...

Avoiding code duplication in Angular: tips for optimizing functions

Is there a way to avoid repeating the same for loop for a second variable and use only one? I'm trying to apply the "Don't repeat yourself" method here. Should I consider using an array? JS: var app=angular.module('xpCalc', []); app.c ...

React Native: Avoiding Infinite Loops in useEffect

I am facing an issue where my app goes into an infinite loop because pointsData is inside the useEffect function. How can I resolve this situation? function useGetPoints() { const [pointsData, setPointsData] = useState<PointTbleType[]>([]); ...

Tips for automatically scrolling images horizontally in responsive layouts

Recently, I've been working on a website called . On the homepage, my portfolio images are arranged in a grid format using the <li> tag. I'm looking to align them side by side and have them scroll horizontally automatically, preferably with ...

I am currently enhancing the country plugin using Javascript by implementing some additional features to suit my specific requirements

Right now I am working on customizing a javascript plugin for countries using jquery. The current code allows me to set the default country value as United Arab Emirates, however, the state is not appearing for the default value. This issue has left me fee ...

Can you achieve a click event in Vue without using $refs?

I have a template structured as follows: <p @click="handleParagraphClick"> <component v-for="item in items" :is="spanComponent"/> </p> The template for the nested span component looks like this: <span ...

Unable to use setState on a component that is not mounted despite already calling componentDidMount

I'm facing a peculiar React Router issue that has me puzzled. Despite the fact that I can confirm the component in question is executing its componentDidMount lifecycle method, I am constantly receiving the warning "Can't call setState (or force ...

Unable to implement new ecmascript decorators within typescript version 2.4.2

Check out this example code: function enumerable(value: boolean) { return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { descriptor.enumerable = value; }; } class A { @enumerable(false) a: number = 1 b: number ...

The camera steadily advances in WebVR Cardboard using three.js technology, never stopping its forward movement

I've been experimenting with trying to create a smooth, continuous forward movement for the camera in a three.js/WebVR project, specifically with only a cardboard viewer needed. After much trial and error, I've discovered that the usual camera m ...

I am converting a class component to a functional component within a React-Redux-Firebase project

I am currently in the process of rebuilding this component. Check out the updated code here Also, take a look at the project actions script here However, I'm facing an issue with rewriting mapStateToProps and mapDispatchToProps functions. The error ...

The updating of React state is occurring, however the component remains unchanged

There is a scenario where an array within the state is being mapped through by a component. When a button is clicked, the state is successfully updated. However, the issue lies in the fact that the component itself is not reflecting these updates. Below ...

Efficient PHP caching solution for optimizing JavaScript and CSS performance

I'm facing a unique challenge that I can't seem to solve through typical Google searches. I'm in the process of consolidating all my javascript and css into separate php files using require_once() to pull in the content. The structure of my ...