Sid Nutthi
Sid Nutthi

Reputation: 161

Javascript For loop iteration count not working

I am trying to push a few objects into an array through a for loop. Although, in that for loop I would like the name of the object to be the current iteration of the for loop. The for loop displayed below runs twice, therefore the Name variable for the first object should be 1 and the name for the second object should be 2. But, in this case for whatever reason, both objects in this array return a Name value of 2. Does anyone know why this would happen?

var ThisArray = [];
var ThisObj = {};

for (var x = 1; x <= 2; x++) {
  ThisObj.Name = x;
  ThisArray.push(ThisObj);
}

console.log(ThisArray);

Upvotes: 1

Views: 408

Answers (4)

8HoLoN
8HoLoN

Reputation: 1142

Your problem is that you push twice the same object.

Here is what you want:

var ThisArray = [];
for (var x = 1; x <= 2; x++) {
    var ThisObj = {};
    ThisObj.Name = x;

    ThisArray.push(ThisObj);
}
console.log(ThisArray);

Upvotes: 0

Carolyn Hodges
Carolyn Hodges

Reputation: 181

You always add the same object. Move the object inside the loop:

const thisArray = [];

for (let x = 1; x <= 2; x++) {
  const thisObj = {};
  thisObj.Name = x;
  thisArray.push(thisObj);
}

console.log(thisArray);

Upvotes: 3

Alberto
Alberto

Reputation: 12949

You are always pushing the same object in the array, and so the second iteration will edit also the one that was previously inserted; instead, you should do something like this:

var obj= {};
for(let x= 1; x<= 2; x++){
    obj= {};
    obj.name = x;
    arr.push(obj);
}
console.log(arr);

so you will change obj every iteration

PS: better version:

for(let x= 1; x<= 2; x++){
    arr.push({name : 2});
}
console.log(arr);

Upvotes: 1

gmiley
gmiley

Reputation: 6604

You are simply reassigning the value of the Name property of the ThisObj to a new value. It is a reference, so you need to create a new instance each time you want to add a new item. Move the variable declaration into the for loop:

var ThisArray= [];
    for(var x= 1; x<= 2; x++){
      var ThisObj= {};
      ThisObj.Name = x;
     
      ThisArray.push(ThisObj);
    }
console.log(ThisArray);

Upvotes: 1

Related Questions