skip to Main Content

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


  1. You could take an empty object as target. This does not mutate given objects.

    const
        a = { d: 1, e: 2 },
        b = { f: 10, g: 20 },
        c = Object.assign({}, a, b);
    
    a.d = 10;
    
    console.log(c); // { d: 10, e: 2, f: 10, g: 20 }
    console.log(a); // { d: 10, e: 2 }
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    Login or Signup to reply.
  2. 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:

    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: 1, e: 2, f: 10, g: 20} as desired
    console.log(A); // { d: 10, e: 2 } as desired
    
    Login or Signup to reply.
  3. You could use a Proxy to create a view over the objects A and B.

    const A = { d: 1, e: 2 };
    const B = { f: 10, g: 20 };
    const C = new Proxy({}, {
      get(target, prop, receiver) {
        return Object.hasOwn(B, prop) ? B[prop] : A[prop];
      },
      ownKeys() {
        return [...new Set(Object.keys(A).concat(Object.keys(B)))];
      },
      getOwnPropertyDescriptor(target, prop) {
        return Object.getOwnPropertyDescriptor(Object.hasOwn(B, prop) ? B : A, prop);
      }
    });
    
    A.d = 10;
    
    console.log(Object.fromEntries(Object.entries(C))); // { d: 10, e: 2, f: 10, g: 20}
    console.log(A); // { d: 10, e: 2 }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search