Adding two comparable Objects in Javascript / vuejs

I have two objects and I want to add the values of each key separately with another object. Here's an example:

CharacterStats: { a: 0, b: 2, c: 0, d: 0 }
ItemStats: { a: 0, b: -1, c: 4, d: 0 }

The expected result is:

CharacterStats: { a: 0, b: 1, c: 4, d: 0 }

I came across this solution on How to sum two object values in JavaScript. However, as I'm working with vueJS, my function looks something like this:

export default {
  data () {
    return {
      CharacterStats: { a:0, b:0, c:0, d:0 }
    };
  },
  methods: {
    calculStatsItems(ItemStats)  {
      var obj = {};
      let self = this;
      Object.keys(self.CharacterStats).forEach(function(a){
        obj[a] = self.CharacterStats[a] + ItemStats[a];
      });
      console.log(obj);
    }
  }
}

However, I keep encountering an error that says "this is undefined" on this line:

Object.keys(this.CharacterStats ).forEach(function(a)

Is there any other way to solve this issue or fix it?

Answer №1

To calculate the sum of values from two objects, follow this approach:

getSumOfValues(items) {
  return items.reduce((a, b) => a + b, 0);
}

calculateTotalStats(data1, data2) {
  const combinedData = [...Object.values(data1), ...Object.values(data2)];
  return this.getSumOfValues(combinedData);
}

Answer №2

When using the .forEach function, it's important to note that the reference to this does not point to the Vue component instance itself. This can lead to the CharacterStats variable being labeled as undefined. To resolve this issue, consider the following implementation:

const CharacterStats = { a: 0, b: 2, c: 0, d: 0 };
const ItemStats = { a: 0, b: -1, c: 4, d: 0 };

new Vue({
  el:"#app",
  data: () => ({
    CharacterStats: { a: 0, b: 2, c: 0, d: 0 }
  }),
  created() {
    this.calculateItemStats({ a: 0, b: -1, c: 4, d: 0 });
  },
  methods: {
    calculateItemStats(ItemStats) {
      const result = {};
      Object.keys(this.CharacterStats).forEach(attr => {
        result[attr] = this.CharacterStats[attr] + (ItemsStats[attr] || 0)
      });
      console.log(result);
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app"></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

Is it possible to launch a hidden tab or window and automatically submit the form within that tab/window?

I have a form for adding users to my Application. After submitting the form, I want to open a hidden TAB/WINDOW where another form is displayed with values retrieved from the database being written to a file. I need this second form to be automatically su ...

Learn how to render list items individually in Vue.js using the 'track-by $index' directive

Recently, I switched from using v-show to display elements in an array one at a time in my Vue instance. In my HTML, I had this line: <li v-for="tweet in tweets" v-show="showing == $index">{{{ tweet }}}</li>". The root Vue instance was set up l ...

Is it possible to configure Nginx to provide HTTPS on port 10000 and implement Basic Auth for an Express app?

My Linux NodeJS/Express application is designed to serve a text file located at http://example.com/secret.txt. I am looking to restrict access to this file only over HTTPS on port 10000 with Basic Auth security measures in place. It's important to no ...

Is it possible to extract data from a table by adjusting Javascript in the inspector tool? The page is only showing today's data, but I'm interested in retrieving historical data by going back

My Desired Action: I am interested in extracting data from the 2nd and 3rd tables on this page. However, the data displayed is specific to the current 'day'. I wish to access readings from September 1st and import them into a Google Sheet. Speci ...

The pie chart fails to fully display

Check out the repro example I made here. The legend is displaying properly, but the graph is not showing up. What could be causing this unexpected issue? ...

Testing asynchronous functions with Mocha

Currently, I am in the process of developing a node wrapper to interface with an external api. One particular challenge I am facing is testing the asynchronous functionality of the createJob method. Provided below is the test case code: api_key = "test_0d ...

next-redux-wrapper is being invoked repeatedly and experiencing multiple calls to HYDRATE

I'm embarking on a new Next.js project, transitioning from a standard React app to a Next.js application. Our plan is to utilize Redux Toolkit for global state management and incorporate server-side rendering. During this process, we discovered the ne ...

The login page allows entry of any password

I'm running a xamp-based webserver with an attendance system installed. I have 10 registered users who are supposed to log in individually to enter their attendance. However, there seems to be an issue on the login page where any password is accepted ...

After closing the box, make sure to hold it securely

After clicking the button and closing my box with jQuery (Toggle), I want the state of the box to be remembered after refreshing the page. If the box was closed, it should remain closed upon refresh, and if it was open, it should stay open. I am looking ...

Updating component data in VueJS can sometimes be tricky, especially when dealing with the same

I have a route called '/posts' which includes a created() function that fetches data from an API using GET and displays the data on the page. Recently, I added a navbar to all pages with an input field for searching posts by tags. This tag-based ...

Creating a Vue.js project using npm or yarn is proving to be a challenge for me

I'm currently facing some challenges when trying to create a Vue.js project using npm or yarn. Here is the command I am using: $ vue init webpack my-project # Installing project dependencies ... # ======================== events. ...

Automated downloading based on operating system recognition

1067/5000 How can I use JavaScript to automatically determine the user's operating system on a webpage and then download the correct installation file? Here is the code I have: HTML <!DOCTYPE html> <html> <body> <iframe id=" ...

Convert the existing JavaScript code to TypeScript in order to resolve the implicit error

I'm currently working on my initial React project using Typescript, but I've hit a snag with the code snippet below. An error message is popping up - Parameter 'name' implicitly has an 'any' type.ts(7006) Here is the complet ...

Clicking on a Vuetify v-btn with the :href attribute set to download will open the XML file

I'm having trouble getting the v-btn to download an XML file instead of opening it in the browser. <v-btn :disabled="!exportUrl" block x-large height="100" color="primary" :href="exportUrl" download> ...

Navigating to the parent node in a treeview within the wijmo flex grid: a step-by-step guide

Utilizing the wijmo flex grid, I've successfully created a tree view for my data. I can determine if a specific node has children and its level, but I'm struggling to navigate to the parent node from a given one. Additionally, I am able to retrie ...

Locating Elements in Protractor: Exploring Nested Elements within an Element that is Also a Parent Element Elsewhere on the Page

<div class="base-view app-loaded" data-ng-class="cssClass.appState"> <div class="ng-scope" data-ng-view=""> <div class="ng-scope" data-ng-include="'partial/navigation/navigation.tpl.html'"> <div class="feedback-ball feedback- ...

Delivering Background Videos with Node.JS

Apologies if my question seems off base or confusing, as I am not very knowledgeable in the world of nodejs. I have been comfortable using just plain PHP and Apache for a while until I discovered ZURB Foundation's stack with Handlebars and SASS, along ...

When using AutoComplete in MUI, I encountered an issue while attempting to assign a default value to the checkbox from an API. Instead of achieving the desired result, I received an error stating "(inter

Within this snippet, I am seeking to retrieve a default value from the API to populate a checkbox initially. I have employed the Material-UI Autocomplete component, which includes a defaultValue prop. Despite my efforts to utilize this prop, I am encounter ...

What is the best way to send multiple values along with an image when uploading to a server using AngularJS and NodeJS?

Client side: Having successfully implemented file upload functionality using AngularJS and NodeJS, I am facing an issue where I need to pass 'name' and 'email' parameters to the server along with the uploaded file. Server side: Once ...

The dynamic alteration of BackgroundImage does not appear to be functioning correctly with tailwind and nextjs

Introduction While working on my weather application using nextJS and TailwindCSS, I encountered a UI issue towards the end of development. Unfortunately, I couldn't resolve this problem alone. My main concern is changing the background image dynami ...