I have an object that I want to replace.
var obj1 = { x: "a" };
var ref = obj1;
var obj2 = { y: "b" };
obj1 = obj2;
This results in ref
being equivalent to { x: "a" }
, but I want it to get changed as well to point to obj2
to get ref
being equivalent to { y: "b" }
.
Object. assign is copying the activities object, but still keeps references to it, so if I find a specific activity and change some property on it, it changes the original too!
TL;DR: There are NO pointers in JavaScript and references work differently from what we would normally see in most other popular programming languages. In JavaScript, it's just NOT possible to have a reference from one variable to another variable. And, only compound values (Object, Array) can be assigned by reference.
Not possible. JS passes objects by a copy of the reference, so in the step var ref = obj1
you're not actually assigning a reference pointer like you would in a language like C. Instead you're creating a copy of a reference that points to an object that looks like {x: 'a'}
.
See this answer for other options you have: https://stackoverflow.com/a/17382443/6415214.
You can try to change all the fields of obj1 with the fields of obj2
var obj1 = { x: 'a' };
var ref = obj1;
var obj2 = { y: 'b' };
obj1.x = obj2.y;
console.log(ref) // Print {x, 'b'}
If you want to add {y,'b'} you can follow the approach
obj1.y=obj2.y
console.log(obj1); prints {x: "b", y: "b"}
console.log(ref); prints {x: "b", y: "b"}
If you instead want to delete obj1.x you can do something like this
delete obj1.x;
console.log(ref) prints {y:'b'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With