Tips for Accessing Values in a Dynamic Array in Vue.js

ArrayOrdered :[ { name :"PRODUCT 1", price :"20", amount:"10", Total 1:" ", discount : "" , Total 2:" " }, { name :"PRODUCT 2", price :"50", amount:"20", Total 1:" ", discount : "" , Total 2:" " }, { name :"PRODUCT 3", price :"15.5", amount:"10", Total 1:" ", discount : "" , Total 2:" " }, ................ ]

I need to calculate the value of Total 1 (price * amount) and Total 2 (Total1 * discount) after each addition to the array and then sum up all the total prices

Answer №1

Instead of directly altering your data, you can utilize a computed property to generate a new version of your list with the necessary items included. This approach is generally considered to be less prone to errors and easier to comprehend. Check out this functional example:

<template>
  <div>
    <ul>
      <li v-for="(item, index) in itemsWithTotals" :key="index">
        <span>{{ item.total1 }} - {{ item.total2 }}</span>
      </li>
    </ul>
  </div>
</template>
const ITEMS = [
  { name: 'item1', price: 20, amount: 10, discount: 0 },
  { name: 'item2', price: 50, amount: 15, discount: 0.25 },
  { name: 'item3', price: 35, amount: 20, discount: 0.75 },
];

export default {
  data() {
    return { items: ITEMS };
  },
  computed: {
    itemsWithTotals() {
      return this.items.map(item => {
        const total1 = item.price * item.amount;
        const total2 = total1 * (1 - item.discount);
        return { ...item, total1, total2 };
      });
    },
  },
};

Note that I have updated your original data to have numerical properties instead of strings.

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

No results appearing in the output section

While developing a website using React, I encountered an error that said useState is defined but never used in the navbar component. To address this, I made changes to my ESLint configuration in the package.json file: "rules": { "eqeqe ...

The Art of Validating Forms in Vue.js

Currently I am in the process of developing a form with validation using Vue, however, I've run into some errors that are showing up as not defined even though they are currently defined. HTML <form class="add-comment custom-form" @submit="checkF ...

transmit JSON formatted form data to an AngularJS platform

I have a webpage built on AngularJS with a login feature. I want to iframe this webpage onto my own page and automatically log in my users. Upon inspecting the AngularJS site, I noticed that the login procedure expects a json object. I have tried multipl ...

The image fails to load when attempting to retrieve it from a local JSON file

I successfully managed to fetch data dynamically from a local JSON file created in RN. However, when I tried to add images for each profile to be displayed along with the dynamic profile info, the app encountered an error stating that "The component cannot ...

Discover the correct steps to transition from using particles.js to the react-tsparticles package

Migrating from react-particles-js to react-tsparticles-js Hi there! I'm currently facing an issue with my ReactJS website here, which is deployed using Netlify. The error code below keeps popping up, and I believe it's related to the transition ...

Is it possible to track unsuccessful email deliveries using MailApp?

In my Google Script program, I incorporate MailApp in the following manner: MailApp.sendEmail(AddressStringGlobal,EMailSubjectProperLanguageGlobal,"",{htmlBody: EMailBody}); The issue arises when I encounter a bad email address in my data set, causing my ...

The document.ready function does not seem to be functioning properly within an iframe

In the main page, there's an embedded iframe set up like this: <iframe src="facts.php" style="width:320px; height:500px; border:hidden" id="facts"> </iframe> Within that iframe, a jQuery function is implemented as follows: <script ty ...

Not all databases are retrieved in the search query

When I make an API call to get all the Database entries, I am encountering an issue. The response I receive only includes a few databases instead of all of them. async function checkDatabases(item){ if(item.object == 'database') ...

What could be causing my React function to be declared but not utilized?

Struggling with my React project, I hit a roadblock when trying to import my generalInput file into my App file. The error message stated that the generalInput was declared but never read. Desperate for a solution, I even turned to AI for help, but it too ...

Issue with ReactJS and Material UI: FlexGrow functionality malfunctioning

I'm currently grappling with the implementation of FlexBox, particularly in understanding how to effectively utilize flexGrow. Despite my efforts, I haven't been able to achieve the desired result as the background appears to only wrap around the ...

Develop a reusable block of Vue template when creating a new component

There are times when I find myself needing to repeat certain sections of HTML code in my Template just to keep it DRY. However, creating a new component and passing multiple props and dynamic data seems like too much work. Is there a simpler way to define ...

What are the steps to ensure compatibility with relative paths when transitioning from v5 to v6?

In my application, there are scenarios where multiple routes must pass through a component before rendering specifics. Additionally, there are situations where something is displayed for the parent route and then divided for the children. It's crucia ...

What is the best way to assign the value of an HTTP GET request to a subarray in Angular 8

Attempting to store data in a sub-array (nested array) but despite receiving good response data, the values are not being pushed into the subarray. Instead, an empty array is returned. for (var j=0;j<this.imagesdataarray.length;j++){ this.http.g ...

Accessing Google Feed API to retrieve media thumbnails

I am currently utilizing the Google Feed API to extract a thumbnail from an RSS feed ("media:thumbnail") The media:thumbnail element in the RSS feed is structured as follows: <media:thumbnail url="http://anyurl.com/thumbnailname.jpg" width="150" heigh ...

Validation of OpenAPI requests on the client-side using React libraries

Is there a way to validate a request against a specific openAPI spec on the client side in a browser environment? I've spent countless hours searching and trying various openapi-tools, but all seem to be geared towards nodejs usage and not suitable f ...

Guide on replacing buttons with <a> tags in express.js posts

I've incorporated handlebars as my chosen templating engine and I'm utilizing buttons to trigger app.post() in my JavaScript file. <form method="POST" action="/smo_assessment"> <div class="container" id="div1"> <h3 id="header" ...

Tips for integrating Excel files with NestJS

I'm in the process of developing a REST API that will utilize a third-party API to retrieve specific status information. The URLs needed for this API are stored in an Excel file, which is a requirement for this use case. My goal is to extract the URLs ...

Having trouble rendering to the framebuffer due to issues with the texture

In the process of incorporating shadow maps for shadows, I am attempting to render a scene to a separate framebuffer (texture). Despite my efforts, I have not been able to achieve the desired outcome. After simplifying my codebase, I am left with a set of ...

Utilize Bootstrap-Vue to ensure that an element expands to occupy the available space

In my Bootstrap-Vue application, I have set up the following hierarchy: <b-navbar.../> <b-container > <b-row align-v="center" style="min-height:100vh"> <b-col style="align-items:center"> <h1>404 Error&l ...

Steps for displaying nested JSON data in VueJS:

After diving into VueJS, I decided to create a table using a JSON file. Although I successfully generated the table, I'm facing an issue with removing three empty rows located above the actual data. Any suggestions on how I can resolve this? test.js ...