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 undifined" on this line:

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

Is there another way to do it or fix it?

Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
Mathieu Barco
  • 81
  • 1
  • 5
  • Does this answer your question? [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Heretic Monkey Feb 06 '21 at 22:14

2 Answers2

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);
}
AdriSolid
  • 2,570
  • 1
  • 7
  • 17
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>
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48