7

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" }.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Chris
  • 13,100
  • 23
  • 79
  • 162

2 Answers2

3

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.

Community
  • 1
  • 1
Charles
  • 640
  • 5
  • 21
1

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'}
Md Johirul Islam
  • 5,042
  • 4
  • 23
  • 56