Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

237
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda