1

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);
1
  • Use let x=1, instead of var Commented Jul 21, 2020 at 18:31

4 Answers 4

3

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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);

1 Comment

Thank you so much! I would upvote it, but I don't have enough points yet.
1

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);

1 Comment

Thank you so much! I would upvote this as well, but I don't have enough points yet.
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.