Search code examples
javascriptclassecmascript-6mergeinstance

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.


Solution


  • 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.