0

I have an object and I need to sum every value independently with another similar object like in this example :

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

The result should be:

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

I found this answer How to sum two object values in javascript But I'm using vueJS so my function looks something like this:

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

But I keep getting an error telling me

This is undefined

on this line:

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

Is there another way to do it or fix it?

1

2 Answers 2

1

You can get the values of both objects, and then make the operation, doing something like:

sum(values) {
  return values.reduce((a, b) => a + b, 0);
}

calculStatsItems(arr1, arr2) {
  const prepareData = [...Object.values(arr1), ...Object.values(arr2)];
  return this.sum(prepareData);
}
Sign up to request clarification or add additional context in comments.

Comments

0

In the .forEach function, this doesn't refer to the vue component instance, so CharacterStats becomes undefined. Try this:

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.calculStatsItems({ a: 0, b: -1, c: 4, d: 0 });
  },
  methods: {
    calculStatsItems(ItemsStats) {
      const obj = {};
      Object.keys(this.CharacterStats).forEach(a => {
        obj[a] = this.CharacterStats[a] + (ItemsStats[a] || 0)
      });
      console.log(obj);
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app"></div>

2 Comments

I only took the method itself and it worked like a charm ! Thank you very much
You're welcome! arrow-functions solved the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.