Reputation: 81
I am not sure what's going on with this, probably I am doing something wrong, but to be honest, I cannot see what's the point. Just take a look at this code and see what happens:
var object = {
one: "one",
two: "two"
};
var object2 = {}
object2 = object;
object["three"] = "what?"
console.log(object2);
The output for the object2
should be {one: "one", "two": two"}
, however it returns {one: "one", "two": two", "three": "what?"}
So why is this happening? I am not modifying object2
, but it gets updated after the push of new value. How can I solve this? I just want to keep the object2
like before. Thanks
Upvotes: 0
Views: 226
Reputation: 416
object2 references object (points to the same reference in memory)
i assume you want to create object2 that is a copy of the first one, which you can do like this:
var obj2 = Object.assign({}, object);
or
var obj2 = {...object}
you can check Object assign MDN, or just google about spread operator syntax
Upvotes: 4
Reputation: 29
When you assign object to object2, it is reference is given to object2. Hence when you add 'three':'what?' to object and print object2, it will be same.
Upvotes: -1