How to copy object properties to another object by reference

89 views Asked by At

I want to be able to bundle the properties of multiple objects into another object by reference, such that when I change the properties in the bundle object it mutates the original objects. I'm using the spread operator to assign the object properties to the new object.

objectA = {"key1" : 1, "key2" : 2, "key3" : 3}
objectB = {"key4" : 4, "key5" : 5, "key6" : 6}

bigObject = {...objectA, ...objectB}
bigObject["key1"] = 50;

Logger.log(bigObject["key1"]) //outputs 50
Logger.log(objectA["key1"]) //outputs 1

I know Javascript copies by value unless you're copying objects, but I don't want an object of objects, I want an object of properties from other objects. Is there any way to achieve this? Thanks in advance.

1

There are 1 answers

1
Sahab On
hope below code can help 


const rebuildMergedObject  = () => {

  for (const prop in bigObject) {
    if (bigObject.hasOwnProperty(prop) && prop !== "sourceObjects") {      
      for (const sourceObject of bigObject.sourceObjects) {
        
        if(sourceObject.hasOwnProperty(prop) ) {
            sourceObject[prop] = bigObject[prop];
        }
        
      }
    }
  }

};


var objectA = {"key1" : 1, "key2" : 2, "key3" : 3}
var objectB = {"key4" : 4, "key5" : 5, "key6" : 6}
var bigObject = { ...objectA, ...objectB };
bigObject.sourceObjects = [objectA, objectB];
bigObject["key1"] = 50;

rebuildMergedObject();

console.log(bigObject); 
console.log(objectA);