Reputation: 151
JavaScript:
var songs = {};
var song = {};
var row = 0;
$('button').on('click', function(){
row++
song['name'] = 'hey' + row;
songs['row' + row] = song;
console.log(songs);
});
every time i click the button it should create a new ['name'] and push it to the object 'songs'. After 5 clicks i expected the object to look like this:
{ "row1": {
"name": "hey1"
},
"row2": {
"name": "hey2"
},
"row3": {
"name": "hey3"
},
"row4": {
"name": "hey4"
}
"row5": {
"name": "hey5"
}
}
But instead it looked like this
{ "row1": {
"name": "hey5"
},
"row2": {
"name": "hey5"
},
"row3": {
"name": "hey5"
},
"row4": {
"name": "hey5"
}
"row5": {
"name": "hey5"
}
}
I think it has something to do with
songs['row' + row] = song;
https://jsfiddle.net/yhk81zbu/3/
Why doesn't this work and how can i fix it?
Upvotes: 4
Views: 70
Reputation: 771
You are storing an object with one property into successively named properties in your songs object. However, in your loop you are updating the same property of the same global song object, so all instances/copies of the song object property 'name' reflects the latest change in the loop. Instead write something like:
var songs = {};
//don't define your object here
var song;
var row = 0;
var songtext;
$('#button').on('click', function(){
row++;
songText = 'hey' + row;
//create a new object each time instead of trying to update the same 'name' property
//of the global song object
song = {name: songText};
songs['row' + row] = song;
console.log(songs);
});
Upvotes: 1
Reputation: 236
You only have one instance of the song object that's being shared in row1, row2, row3 etc. Every time you write song['name'] = 'hey' + row;
you're modifying the 'name' field of the one song object, which remember is being shared by all of the rows. You have to make sure you create a new song object each time so instead of song['name'] = 'hey' + row;
you can write var song = {'name' : 'hey' + row };
and that way each row will have its own song object instead of sharing one.
var songs = {}
var row = 0;
$('button').on('click', function(){
row++
var song = {'name' : 'hey' + row };
songs['row' + row] = song;
console.log(songs);
});
Upvotes: 7