问题
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 i get the values from obj2 on common properties, but when i do the same with root which is an HTML element i don't get its values (for example the value of id property)
const root = document.getElementById("root");
const obj1 = { id: "obj1", textContent: "i am obj1" };
const obj2 = { id: "obj2", textContent: "i am obj2"};
const merged1 = Object.assign({}, obj1, obj2); // the new object got the id and textContent from obj2
const merged2 = Object.assign({}, obj1, root); // the new object got the id and textContent from obj1. why not from root?
console.log(merged1);
console.log(merged2);
console.log(root.id);
console.log(root.textContent);
回答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);
i don't want to override root, i want a new object and get the
relevant values from the root 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);
EDIT: Why when i merged with Object.assign 2 "normal" objects like
obj1 and obj2 i get the values from obj2 on common properties, but
when i do the same with root which is an HTML element i don't get its
values (for example the value of id property)
Object.assign() can copy enumerable properties of an object. HTMLDivElement id and textContent properties are not enumerable.
Object.assign()
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));
来源:https://stackoverflow.com/questions/44348923/merge-html-element-object-with-a-custom-object