Experiencing trouble with calculating the total value of an array of objects due to NaN errors

I've been working on developing this web application in VUE.js, but I'm facing an issue with a specific function where I am attempting to sum the values of each object within an array. This is resulting in a NaN (Not a Number) error. Let's take a look at the code below:

SCRIPT

data(){
 return{
    array:[
      { product_name: "Chain Saw",
       product_free: 2,
       product_free_discount: 306.8,
       product_id: 1,
      },
      { product_name: "Ox",
       product_free: 1,
       product_free_discount: 60.8,
       product_id: 1,
      }
  ],
  totalDiscEquals:0,
 }
}

In my computed property, I have defined the following function:

COMPUTED
totalDiscObUnique() {
      let total = this.array.reduce(
        (a, b) => a + b.product_free_discount,
        0
      );
      console.log(total);

      return this.totalDiscEquals=total;
    },

For the creation process, I used the created module as shown below:

created(){
this.totalDiscObUnique;

However, when checking the value of totalDisEquals using console log, it shows NaN. Any insights on why this might be happening or suggestions for resolving the issue would be greatly appreciated.

Answer №1

new Vue({
  el: '#app',
  
  data: {
    array:[
      { 
        product_name: "Chain Saw",
        product_free: 2,
        product_free_discount: 306.8,
        product_id: 1,
      }, // <--- [1] missing comma here (,)
      { 
        product_name: "Ox",
        product_free: 1,
        product_free_discount: 60.8,
        product_id: 1,
      }
    ],
    totalDiscEquals:0,
  },
  
  /* [2] It's not recommended to assign new value to a data property
 in a computed, instead it is intended to give you just a filtered/reduced
 / ... response.  */
  computed: {
    totalDiscObUnique() {
      return this.array.reduce((a, b) => a + b.product_free_discount, 0);
    },
  },
  
  created () {
    /* [3] also, there is no need to reassign the same value to a new
 data property again, instead you can use the computed itself wherever you
 want to use it */
    // this.totalDiscEquals = this.totalDiscObUnique
    console.log(this.totalDiscObUnique)
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
 {{ totalDiscObUnique }}
</div>

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

Comparison between JSON Serializers and .NET Serialized Classes for Retrieving jQuery AJAX Result Data

What is the best method for transferring data from a .NET (C#, VB.NET) Web Service to the client-side using JQuery AJAX? A) Utilizing Newtonsoft JSON serialization, for example: <WebInvoke(Method:="*", ResponseFormat:=WebMessageFormat.Json, UriTemplat ...

Stop the selection of text within rt tags (furigana)

I love incorporating ruby annotation to include furigana above Japanese characters: <ruby><rb>漢</rb><rt>かん</rt></ruby><ruby><rb>字</rb><rt>じ</rt></ruby> However, when attemp ...

Sending variable boolean values to a VueJS component

How can I assign dynamic properties to a VueJS Component using VuetifyJS? Below is an example of VuetifyJS code that constructs a select field element: <div id="app"> <v-app id="inspire" style="padding: 10px; "> ...

Validate all JavaScript buttons by binding a click event

I've implemented the JS validation plugin from this source and it's functioning properly. However, it captures all button clicks on the page, including when I click on Back to Home, triggering form validation unnecessarily. I only want the form ...

Learn how to implement a feature in your chat application that allows users to reply to specific messages, similar to Skype or WhatsApp, using

I am currently working on creating a chatbox for both mobile and desktop websites. However, I have encountered an obstacle in implementing a specific message reply feature similar to Skype and WhatsApp. In this feature, the user can click on the reply butt ...

ALSO, various criteria

function findLogicalAND(){ let result; let index; for (index = 0; index < arguments.length; index++){ result = arguments[index] && arguments[index+1]; } return result; } console.log(findLogicalAND(true, true, false, false)); I want to r ...

When using Firestore in Android, I encounter a nodejs error regarding headers being sent prematurely

Currently, I am utilizing a webview in order to display content from a nodejs server. While requesting a page works as expected, accessing firestore results in an error where it seems like nodejs is attempting to resend the page. Below is the code for an a ...

Calculate the sum of the products when multiplying two values from every array of objects, using Reactjs/Javascript

I'm currently developing an eCommerce application and need to calculate the total price of items that users have ordered. I have an array named 'orders' which contains all the ordered items, each item has two keys - payablePrice and purchase ...

I am interested in checking the dates of the current date and disabling the button if the date falls within that range

I am attempting to deactivate a button if the current date falls within a three-month period. Despite my efforts to use a combination of Php and JavaScript, I was unable to make it work. PHP Code @php($found = false) @foreach($doctors as $doctor) ...

Error in form action when generated through an ajax partial in Ruby

I am facing an issue with a form that is loaded via an ajax partial. The problem arises when the form loads through ajax as it targets the wrong controller/url instead of the intended one. Despite my efforts to set the target controller correctly, it keeps ...

Incorporating Dynamic Events into HTML Generated on the Fly within a Vue.js Component

Currently, I am facing an issue where I am trying to dynamically generate HTML in a Vue.js component. While I have successfully rendered the HTML, I am struggling to connect the events for these dynamically generated elements. To illustrate this problem, I ...

A method to use jQuery to replace newlines with commas in user input

Input Processing Challenge <input> Whenever there is multi-line text pasted into the input field, I need to replace newlines (\r, \n, and \r\n) as well as tabs \t with commas ,. This scenario mainly occurs when users copy c ...

Dealing with multiple ajax requests while utilizing a single fail callback

Looking for a solution: I have two arrays containing deferreds. In order to detect failures in the outer or inner 'when' statements, I currently need to use double 'fail' callbacks. Is there a way to consolidate errors from the inner &a ...

Ensure that the sidebar automatically scrolls to the bottom once the main content has reached the bottom

I am facing an issue with a sticky sidebar that has a fixed height of calc(100vh-90px) and the main content. The sidebar contains dynamic content, which may exceed its defined height, resulting in a scrollbar. On the other hand, the main content is lengthy ...

A JavaScript function that is only triggered half of the time

After browsing through various forums like StackOverflow, I couldn't find a solution that perfectly fits my issue. I may be new to programming, but I've managed to create several projects already. Currently, I am working on integrating them into ...

Highlighted option selection in Material UI dropdown using Cypress

Can someone explain how to select Material-UI dropdown options using Cypress? I'm looking for a simple explanation, thanks! ...

Implementing key strokes in an HTML input field within a geckoWebBrowser

I am currently using the "geckoWebBrowser1" component to navigate to a URL that displays a login textbox with the ID: login-email Although I have successfully inserted "[email protected]" into the aforementioned textbox, it is essential to simulate k ...

What is the most effective method for populating data within a browser window?

I have a list of files stored in $scope.data that I retrieved from the searchFactory. Now, my goal is to display these files in the browser window. How can I accomplish this task? ctrl.js $scope.displayFiles = function (){ $window.open($scope.dat ...

Can VueJS lifecycle hooks be outsourced?

Is it possible to organize lifecycle hooks (like created / mounted) in a separate file for better simplicity and cleanliness? MyGreatView.vue import created from 'created.js' export default { created, // created() { console.log('vue Cre ...

Sending a value to a different Ionic page based on a specific condition

Here is the code snippet from my app.js: var app = angular.module('dbpjkApps', ['ionic']) app.controller('kategoriCtrl', function($scope) { $scope.listKat = [ {kat: 'math'}, {kat: 'physics'}, ...