Reputation: 5485
I have been working with JavaScript for quite a time, but have never encountered this issue:
var objArr = [];
var obj = {
id:null,
name:''
}
//Type 1: Why This do not work
//create an array of 5 object
for(var i=0; i<3; i++){
obj.id = i;
console.log(obj);
objArr.push(obj); //What is wrong here
}
console.log(JSON.stringify(objArr)); // Have 5 objects in the array, But if you see this object is display the last object
//output : [{"id":2,"name":""},{"id":2,"name":""},{"id":2,"name":""}]
//Type 2: Why This Works and why the above object works
var objArr=[];
//create an array of 5 object
for(var i=0; i<3; i++){
console.log(obj);
objArr.push({"id":i, "name":''});
}
console.log(JSON.stringify(objArr));
//output : [{"id":0,"name":""},{"id":1,"name":""},{"id":2,"name":""}]
Maybe I have miss understood the objects here. can you please tell me why is this behavior.
I have a jsfiddle.net Fiddle
Upvotes: -1
Views: 53
Reputation: 8043
Try to use something like this:
var objArr=[];
for(var i=0; i<3; i++){
var obj = {};
obj['id'] = i;
obj['name'] = null;
console.log(obj);
objArr.push(obj);
}
console.log(JSON.stringify(objArr));
Upvotes: 0
Reputation: 34
You just need to create a new obj inside the first for loop. You're just editing the current obj defined outside the for loop. So each loops sets the id of the one obj to it's i value, then you're inserting a copy of that into the array, so on the next loop, each reference to the original object is changed.
Inside the for loop, I just added 'var' so obj is a new one, not the same one that is in the parent scope:
var obj.id = i;
But you may want to reformat it a bit better than that.
Upvotes: -1
Reputation: 19030
In the first example, you have one (only one) object, obj
. You are creating an array of 3 (not 5) objects, but each position in your array refers to the same object.
When you set obj.id
, you are changing it for the one and only object, which is referenced at each position in the array.
In the second example, you are creating a new object each time:
{"id": i, "name":''} // this creates a new object
So it works.
Upvotes: 0