Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

235
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!