Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

193
Visualizações
I keep loosing the first key/value pair when adding the values

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]

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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));

about 4 years ago · Juan Pablo Isaza Relatório

0

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:

  1. Operate with object keys instead of relying on indices.
  2. "for" loop inside other "for" loop is redundant. Only one iteration is needed.
  3. Return result as object instead of array of numbers (again, indices are easy to mismatch and introduce more bugs to the app).
  4. Function name is confusing. I don't see how you compare stats actually. You only sum values of the same keys - it is different. Rename it to e.g. mergeObjectValues.
  5. Property "armor" is a typo. Expected word is "armour".
  6. Handle possibly undefined values with default "0" value. So you will not receive 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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda