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