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

What is the method for pulling information from MySQL and presenting it on a website using Node.js?

Currently, my goal is to retrieve data from MySQL and showcase it on my HTML page. The code snippet in server.js looks like this: const path = require('path'); const express = require('express'); const bodyParser = require("body-pa ...

What is the best way to include and delete several images on a canvas?

Recently, I've started working with canvas in HTML5 and I'm tasked with creating a paint application. One of the features I need to implement is the ability to dynamically add selected images to the canvas as the mouse moves, and then have the fu ...

Leveraging jquery's $.ajax method to send GET values to a PHP endpoint

Is it possible to use an AJAX call to pass a value to a PHP script? For example, if I have the URL example.com/test.php?command=apple, how can I make sure that the code is executed properly on the server side? This is how my code looks like: PHP: <?p ...

Treating Backbone Collection as an object instead of an array

Currently, I am working on incorporating nested comments using both Backbone and Rails. In my current setup on the server side, comment models are utilized to store the unique identifier parent_comment_id (assuming they have one). Whenever the application ...

Creating a transparent background for a Canvas animation with three.js and dat.gui

I'm struggling to set up a background animation on this canvas using three.js. However, the background renders as black instead of transparent. I attempted to adjust it with CSS by adding background-color:transparent;, but to no avail. I've searc ...

I'm having trouble importing sqlite3 and knex-js into my Electron React application

Whenever I try to import sqlite3 to test my database connection, I encounter an error. Upon inspecting the development tools, I came across the following error message: Uncaught ReferenceError: require is not defined at Object.path (external "path ...

Switching between play and pause for the video element using a component for the child

Trying to toggle the play/pause of a child video by clicking on a parent div can be challenging, especially when dealing with multiple instances of the same div and video. A normal function may only work for one specific video, as mentioned by @ken. I hav ...

What steps do I need to take to ensure that my AJAX button press request functions properly within my Django setup?

Is there a way to utilize a JavaScript string variable in a Python function and then return it back to a JavaScript variable efficiently? Perhaps using Json/ajax can help with this? To start, there is an HTML element where a string is stored: <h2 id=&q ...

Looking to determine if a specific element is assigned multiple class names

Help needed! Can you tell me how to check if an element contains more than one classname using pure javascript, without using jQuery? For example: If #test has both the classnames "classA and classB", then { alert(true) } else { alert(false) } Here is ...

Are Bootstrap Input groups inconsistent?

Hey there! I've been working on the sign-in example, but I seem to have hit a roadblock. In my local setup, the top image is what I see in my browser after running the code, while the desired layout that I found on the Bootstrap site is the one below ...

Why does my anchor disappear after a second when clicked to show the image?

Hi everyone, I'm having an issue with a dropdown menu that I created using ul and anchor tags. When I click on one of the options, an image is supposed to appear. However, the problem is that the image shows up for just a second and then disappears. I ...

What could be causing my selenium tests to fail on travis-ci even though there have been no code changes, when they are passing successfully

I'm facing a tough challenge trying to troubleshoot a selenium test that passes when run locally but not on travis. Reviewing the travis build logs, I noticed that the test was passing in build #311 but started failing at build #312. It seems like th ...

Make sure the variable is present in the store state by utilizing vuex

My application only loads to the DOM if user details are available: <template> <div id="app"> <template v-if="loggedUser"> //... </template> </div> </template> The loggedUser property is a computed valu ...

The initial JavaScript load shared by all users is quite large in the next.js framework

Currently working on a project using the Next.js framework and facing an issue where the First Load JS shared by all pages is quite heavy. I am looking for advice on possible strategies to reduce the weight of the JS file, and also wondering if there ...

Combine two events in jQuery using the AND operator

Can I create a condition where two events are bound by an AND logic operator, requiring both to be active in order for a function to be called? Let's say you have something like this: foobar.bind("foo AND bar", barfunc); function barfunc(e) { al ...

Sending a Boolean value from a child component to its parent state in React JS

Within my application, I have implemented a login feature in the navbar component. However, I am encountering an issue with updating a variable in the main component upon successful login. Although I have successfully managed to set up the login functional ...

Issue encountered when employing the spread operator on objects containing optional properties

To transform initial data into functional data, each with its own type, I need to address the optional names in the initial data. When converting to working data, I assign a default value of '__unknown__' for empty names. Check out this code sni ...

Run javascript code after the page has transitioned

Struggling to create a dynamic phonegap app with jQuery Mobile, the issue arises when loading JavaScript on transition to a new page. The structure of my index page is as follows: <body> <div data-role="page" id="homePage"> <div data- ...

Dispatch in React Redux is not intercepted

I've been grappling with this issue for hours and still can't seem to find a solution. When I click the button, the function "getLocation" is being triggered (Confirmed it) However, the dispatch is not getting passed to the reducer. After r ...

Obtaining a worldwide JavaScript variable through AJAX JSON query

Hello, I have encountered an issue while using this code for my AJAX JSON request. When attempting to make jsonObj a global variable and then console.log() it, the debugger console shows that it is always coming up as undefined. To explain my question fur ...