简体   繁体   English

将对象属性绑定到另一个对象的属性

[英]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++.我想创建一个新对象,为它的属性分配来自另一个对象的一些值,我想“绑定”它 - 就像在 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.每当我修改assignObject['obj1a'] ,我希望它也反映在object1['obj1']['obj1a']

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?我怎样才能在 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/这是小提琴: https : //jsfiddle.net/ha2qcdko/

Thanks!谢谢!

If you get the object reference, it will work as you expect:如果您获得object引用,它将按您的预期工作:

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 .但是一旦你的引用是object1['obj1']['obj1a'] ,那不再是一个object ,它是一个string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM