Merge Html Element Object With A Custom Object
I'm trying to figure out why I can't merge 2 or more objects when one of them is an HTML Element. EDIT: Why when i merged with Object.assign 2 'normal' objects like obj1 and obj2
Solution 1:
Pass root
as first parameter to Object.assign()
const root = document.getElementById("root");
const obj1 = { id: "obj1", textContent: "i am obj1" };
const obj2 = { textContent: "i am obj2"}
const merged = Object.assign(root, obj1, obj2);
console.log(merged);
console.log(root.id);
console.log(root.textContent);
<divid="root">i am root</div>
i don't want to override
root
, i want a new object and get the relevant values from theroot
object.
const root = document.getElementById("root");
const obj1 = { id: "obj1", textContent: "i am obj1" };
const obj2 = { textContent: "i am obj2"};
const {id, textContent} = root;
const merged = Object.assign({}, obj1, obj2, {id, textContent});
console.log(merged);
console.log(root.id);
console.log(root.textContent);
<divid="root">i am root</div>
EDIT: Why when i merged with
Object.assign
2 "normal" objects likeobj1
andobj2
i get the values from obj2 on common properties, but when i do the same withroot
which is an HTML element i don't get its values (for example the value ofid
property)
Object.assign()
can copy enumerable properties of an object. HTMLDivElement
id
and textContent
properties are not enumerable.
The
Object.assign()
method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
const root = document.getElementById("root");
const props = ["textContent", "id"];
for (const prop of props) console.log(Object.propertyIsEnumerable(root, prop));
<divid="root">i am root</div>
Post a Comment for "Merge Html Element Object With A Custom Object"