-1

I have a global Javascript object for which I set some values and push to an array. Once I push it to my array and update its values, it changes the already pushed values in the array. For example:

let obj1 = {"name":"", "age":""} //Assume this is declared outside the scope of the below block

{
    obj1.name = "john";
    obj1.age = 21;
    arr1.push(obj1);

    console.log(arr1) // [{name:"john", age:21}]
    
    obj1.name = "mary"; //Object in array has already changed here
    console.log(arr1) // [{name:"mary", age:21}]
    obj1.age = 24;

    arr1.push(obj1)
 
}

I want to understand why this happens and how I can avoid it from happening. I want to be able to push 2 different objects with different values to the array. Is the only way to do this by creating another object?

jaimish11
  • 536
  • 4
  • 15
  • 2
    because it is the same object. You are pushing a reference to the object. You are not making a copy of it each time you push. – epascarello Jul 13 '20 at 14:06
  • 1
    *"I want to be able to push 2 different objects with different values to the array. Is the only way to do this by creating another object?"* - It sounds like you answered your own question right there. Consider the semantics of what you just stated... If I want to have two objects, do I need to create two objects? Yes. – David Jul 13 '20 at 14:08

1 Answers1

2

I want to understand why this happens

You created an object. You pushed it into an array. You modifed that object. You pushed it into the array again.

Is the only way to do this by creating another object?

Yes. If you want two different objects, then you have to create two different objects.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335