TehShrike / deepmerge

A library for deep (recursive) merging of Javascript objects
MIT License
2.75k stars 216 forks source link

Is it possible to deepmerge an HTML dom object? #221

Closed saifeiLee closed 2 years ago

saifeiLee commented 3 years ago
const slotElm = document.getElementById('test-btn');
    const obj_1 = {
      slot: slotElm,
    };
const obj_2 = deepmerge({ name: 'test' }, obj_1);
console.log('after merge:', obj_2)
截屏2020-12-08 下午5 02 45

Run this code snippet, i got the error above. It seems that deepmerging an html element is not supported. Could anyone tell me the reason of that? Thanks a lot~~~

RebeccaStevens commented 3 years ago

Look like the problem you have here is slotElm isn't a "plain object" and deepmerge is using its default cloning under the hood which only handles cloning of "plain objects".

There are 2 easy solutions to fix this. Either tell deepmerge to not clone by setting the clone option to false, or tell deepmerge that DOM Objects are not mergeable (/cloneable) by setting the isMergableObject option (see: https://github.com/TehShrike/deepmerge#ismergeableobject - you probably want to use is-plain-object).

AndrewRedican commented 3 years ago

It is unlikely this will be supported. Unless the implementation used symbol to track where the algorithm has traversed. DOM objects have references to itself this is why you get RangeError, it is likely to be causing infinite recursion at fails after 50 levels of depth or so.

TehShrike commented 2 years ago

Also I believe most DOM elements have internal state that prevents them from being cloned by userland code.

You probably want Node.cloneNode()