Jonathan Jonathan - 3 months ago 6
Javascript Question

obj[key].newKey = val isn't stored

I'm trying to assign a value to an object property but it isn't stored.

for (var i = 0; i < players.length; i++) {
if (players[i].volume < 1) players[i].volume = (Math.round((players[i].volume + 0.1) * 10) / 10); // JS math error fix
settings[players[i].id] = settings[players[i].id] || players[i].id;
settings[players[i].id].volume = players[i].volume;
console.log(settings[players[i].id] + " " + players[i].id + " " + players[i].volume + " " + settings[players[i].id].volume);
}


settings[players[i].id].volume
==
undefined


Fiddle



How can I store the volume?

Answer

If you add some property dynamically to settings, you should first initialize it. Initialization can be done using an empty object literal, like this:

settings[player[i].id] = {};
settings[player[i].id].volume = player[i].volume;

You wrote:

settings[players[i].id] = settings[players[i].id] || players[i].id;

that can assign players[i].id to the settings[players[i].id], which is not an Object.

You should check the type of settings[players[i].id], then assign something to it:

settings[players[i].id] = settings[players[i].id] || players[i].id;
Comments