-1

I've got 2 arrayys and I want to add the values of each of the keys together

const baseStats =  { CHA: 2, CON: 1, DEX: 1, HP: 12, INT: 1, STR: 2, WIS: 1 };
const bonusStats = { CHA: 0, CON: 0, DEX: 0, HP: 2,  INT: 0, STR: 2, WIS: 1 };

Expected result = { CHA: 2, CON: 1, DEX: 1, HP: 14, INT: 1, STR: 4, WIS: 2 };

micnil
  • 4,705
  • 2
  • 28
  • 39
Bill
  • 4,614
  • 13
  • 77
  • 132

3 Answers3

1

Can you try to do this?

var result = {};

for(var key in baseStats){
    result[key] = baseStats[key] + bonusStats[key];
}

console.log(result);
webprogrammer
  • 2,393
  • 3
  • 21
  • 27
0

An alternative to @webprogrammer 's answer, assume the two objects you have has distinct keys:

let result = {};

for (let [key, value] of Object.entries(baseStats)) {
   result[key] = bonusStats[key] + value
}

You can read this if you want to know more about entries.

Andus
  • 1,713
  • 13
  • 30
0

Another alternative, I use Object.keys and forEach

const result = {};
Object.keys(baseStats).forEach(key => result[key] = baseStats[key] + bonusStats[key]);

I've edited it based on the comment.

  • 1
    You should use `.forEach` instead of `.map()` if all you're going to use it for is iteration and causing side-effects. `.map()` is used when you want to convert each element in the array to something else (ie: map each element to something else). So `.map()` returns the changed array. You're not using the returned value of `.map()` here, so `.forEach()` would be better here ;) – Nick Parsons Feb 01 '20 at 13:22
  • 1
    Yes, I agree. My mistake, I've edited the answer. – Kamil Augustyniak Feb 01 '20 at 13:24