So I want to run two objects through this function, have it compare the keys and then add the values of the keys that match. For some reason, it's just chopping off the first key/value pair and I'm not sure why. My guess is something to do with the nested for loops but I can't seem to wrap my head around where the malfunction is.
const necro = {
health: 6,
attack: 2,
armor: 4,
focus: 0,
speed: 0,
recover: 10,
}
const baseCharacter = {
health: 8,
attack: 8,
armor: 8,
focus: 8,
speed: 8,
recover: 8,
}
const statCompare = (myObj,staticObj) => {
let myVal = Object.values(myObj)
let baseVal = Object.values(staticObj)
let newVal = []
for(let i = 0; i < myVal.length;i++) {
for(let j = 0; j < baseVal.length;j++){
if (i=j){
statSum = myVal[i] + baseVal[j]
newVal.push(statSum)
}
}
}
return newVal
}
npcStats = statCompare(necro, baseCharacter)
console.log(npcStats)
console.log returns [10,12,8,8,18]
const necro = {
health: 6,
attack: 2,
armor: 4,
focus: 0,
speed: 0,
recover: 10,
}
const baseCharacter = {
health: 8,
attack: 8,
armor: 8,
focus: 8,
speed: 8,
recover: 8,
}
const statCompare = (myObj, staticObj) => {
const result = [];
for (let [k1, v1] of Object.entries(myObj)) {
for (let [k2, v2] of Object.entries(staticObj)) {
if (k1 === k2) result.push(v1 + v2);
}
}
return result;
}
console.log(statCompare(necro, baseCharacter));
Do not rely on index of object values to compare different objects. It is error prone approach. Instead, rely on object keys.
Actually I have multiple notes on your code:
mergeObjectValues.NaN.Therefore, a better code is like next:
const necro = {
health: 6,
attack: 2,
armour: 4,
focus: 0,
speed: 0,
recover: 10,
}
const baseCharacter = {
health: 8,
attack: 8,
armour: 8,
focus: 8,
speed: 8,
recover: 8,
}
const mergeObjectValues = (myObj, staticObj) => {
const result = {};
// keys should be from object with full list of possible keys
const keys = Object.keys(myObj);
keys.forEach(k => {
const v1 = myObj[k] || 0;
const v2 = staticObj[k] || 0;
result[k] = v1 + v2;
});
return result;
}
console.log(mergeObjectValues(necro, baseCharacter));
Result is clear and easy to work with further:
{
"health": 14,
"attack": 10,
"armour": 12,
"focus": 8,
"speed": 8,
"recover": 18
}
If you really need just an array of numbers and order is not important, this is the place where you use Object.values