简体   繁体   中英

Deep merge two class instances

How do I properly deep merge ( lodash like) two ES6 class instances ?
The resulting object has to be an actual instance of the same class and its properties should be a deep merge of the two instances' properties.


If there is no need to create a new instance, the following will do

_.merge(instance1, instance2)

This will deep merge instance2 properties into instance1 while preserving the prototype.


If the merged instance should be a brand new object it is still achievable:

let newInstance = Object.assign(Object.create(Object.getPrototypeOf(o1)), _.merge(o1, o2));

This will create a new object which is an instance of the same class o1 is and will deep merge into it the properties of o1 and o2 .
This approach, however, has some caveats, for example (from here ):

It's hardly possible if the instance was created with heavy use of closures in the constructor function. We may never now which internal values were set, and how to reproduce such a setup.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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