leuemon
leuemon

Reputation: 46

iteratively adding to an array of objects in Javascript

I am trying to create an object iteratively with the following structure:

    var series = {
        data: [{
            name:  'some text',
            y: 0
        },
        {
            name:  'some other text',
            y: 1
        }]
    }

Below is my code so far:

var series = {
    data: []    
};

var datatemp = {
    y: '',
    name: ''
};

for (var i=0; i<10; i++) {
    datatemp.y = i;
    datatemp.name = "namelabel"+i;
    series.data.push(datatemp);
}

But what I am getting is the final values of series.data[i].y and series.data[i].name in all elements of the array, rather than what I expect, which is different values as the counter i iterates. I would appreciate your guidance on what I am doing wrong. Thanks in advance!

Upvotes: 1

Views: 2268

Answers (4)

stewe
stewe

Reputation: 42642

Objects are passed by reference in javascript, in your example you only have one object which is referenced by the name datatemp, every time you assign a new value to one of its members the old member gets overwritten, so you have to create a new object for each iteration of the loop.

Upvotes: 0

Baz1nga
Baz1nga

Reputation: 15579

var series = {
    data: []    
};



for (var i=0; i<10; i++) {
    var datatemp={};
    datatemp.y = i;
    datatemp.name = "namelabel"+i;
    series.data.push(datatemp);
}

for (var i=0; i<10; i++) {
    console.log(series.data[i].y);
        console.log(series.data[i].name);
}

http://jsfiddle.net/Vp8EV/

Upvotes: 0

jfriend00
jfriend00

Reputation: 707416

To add to what Mimisbrunnr said, you could even do it this way:

for (var i=0; i<10; i++) {
    series.data.push({y: i, name: "namelabel"+i});
}

There is no need for the intermediate variable.

Upvotes: 5

zellio
zellio

Reputation: 32484

You need to make a new datatemp for each iteration of the for loop otherwise you are just passing the same object into the array each time and modifying it's values.

for (var i=0; i<10; i++) {
    var datatemp = {};
    datatemp.y = i;
    datatemp.name = "namelabel"+i;
    series.data.push(datatemp);
}

Upvotes: 1

Related Questions