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

236
Visualizações
Incrementing property value in an object based on reoccurring property name in JavaScript

I ran into a problem with value incrementation, the value is inside of an object and I need to increment it. I am adding new properties and values to and Object and I am using a for loop. I am adding the new properties and values via if/else statement.

Here is the data I am using in this assignment.

const game = {
  team1: 'Bayern Munich',
  team2: 'Borrussia Dortmund',
  players: [
    [
      'Neuer',
      'Pavard',
      'Martinez',
      'Alaba',
      'Davies',
      'Kimmich',
      'Goretzka',
      'Coman',
      'Muller',
      'Gnarby',
      'Lewandowski',
    ],
    ['Burki', 'Schulz', 'Hummels', 'Akanji', 'Hakimi',
     'Weigl', 'Witsel', 'Hazard', 'Brandt', 'Sancho', 'Gotze'],
  ],
  score: '4:0',
  scored: ['Lewandowski', 'Gnarby', 'Lewandowski', 'Hummels'],
  date: 'Nov 9th, 2037',
  odds: {
    team1: 1.33,
    x: 3.25,
    team2: 6.5,
  },
};

And here is the for loop I am trying on this data, for clarification: I am trying to inject new properties with values into an empty Object.

for (var i = 0; i < game.scored.length; i++) {
  if (!(`${game.scored[i]}` in scorers)) {
    Object.defineProperty(scorers, `${game.scored[i]}`, {
      value: 1,
    });
  } else if (`${game.scored[i]}` in scorers) {
    scorers[game.scored[i]]++;
  } else {
    scorers[game.scored[i]] = 1;
  }
}
console.log(scorers);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your issue is an improper configuration of the Object.defineProperty method. The third parameter, the descriptor, has a writable key which determines whether or not the value can be changed (it defaults to false). That said, it's generally preferable to assign new key/value pairs to an object using the following notation: object[key]=value So your particular chunk of code could be re-written as


     if(!(`${game.scored[i]}` in scorers)){
                 scorers[game.scored[i]] = 1
            }

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