javascriptvue.jsobject

How to sum two similar Objects in Javascript / vuejs


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?


Solution

  • 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>