Search code examples
javascriptnode.jsobjectjavascript-objects

Bind object properties to another object's properties


I want to create a new object, assign its property some values from another object and I want to 'bind' it - like pass by reference in C++.

So in this example below:

var object1 = {
    'obj1' : {
    'obj1a' : 'a',
    'obj1b' : 'b'
  },
  'obj2' : {
    'obj2c' : 'c',
    'obj2d' : 'd'
  }
}

var assignObject = {}
assignObject['obj1a'] = object1['obj1']['obj1a']
assignObject['obj1a'] = 'bbb'

console.log('assignObject' + JSON.stringify(assignObject))
console.log('object1' + JSON.stringify(object1))

Whenever I modify content of assignObject['obj1a'], I want it to reflect on object1['obj1']['obj1a'] as well.

var assignObject = {}
assignObject['obj1a'] = object1['obj1']['obj1a']  // this is my idea of 'binding'
assignObject['obj1a'] = 'bbb'  // and updating of assignObject['obj1a']

Console prints:

assignObject{"obj1a":"bbb"}
object1{"obj1":{"obj1a":"a","obj1b":"b"},"obj2":{"obj2c":"c","obj2d":"d"}}

And I want it to print:

assignObject{"obj1a":"bbb"}
object1{"obj1":{"obj1a":"bbb","obj1b":"b"},"obj2":{"obj2c":"c","obj2d":"d"}}

How can I do this in Javascript? Do note that there will be multiple parameters and they will be dynamic in real code (undefined depth nested objects).

Here is the fiddle: https://jsfiddle.net/ha2qcdko/

Thanks!


Solution

  • If you get the object reference, it will work as you expect:

    const object1 = {
      'obj1' : {
        'obj1a' : 'a',
        'obj1b' : 'b'
      },
      'obj2' : {
        'obj2c' : 'c',
        'obj2d' : 'd'
      }
    }
    
    let assignObject = object1.obj1;
    assignObject.obj1a = "bbb";
    
    console.log(object1);
    

    But once your reference is object1['obj1']['obj1a'], that is not an object anymore, it is a string.