Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pushing to object not working correctly in JavaScript

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?

like image 680
Joost Hobma Avatar asked Feb 09 '23 01:02

Joost Hobma


1 Answers

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);
});
like image 177
goodface87 Avatar answered Feb 11 '23 01:02

goodface87