I have objects A and B and would like pass properties of A into B by reference, without passing B’s props into A. I.e.:
const A = { d: 1, e: 2 };
const B = { f: 10, g: 20 };
const C = Object.assign(A, B);
A.d = 10;
console.log(C); // { d: 10, e: 2, f: 10, g: 20} as desired
console.log(A); // { d: 10, e: 2, f: 10, g: 20} but would like just { d: 10, e: 2 }
Is there a way to do this, without using functions/getters to copy things?
3
Answers
You could take an empty object as target. This does not mutate given objects.
Yes, you can use the spread operator to copy the properties of object A into a new object, and then use Object.assign to merge that new object with object B. This will create a new object with the properties of A and B, without modifying either of the original objects. Here’s an example:
You could use a
Proxy
to create a view over the objectsA
andB
.