Html merge方法,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 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);

i am root

回答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 am root

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);

i am root

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));

i am root

来源:https://stackoverflow.com/questions/44348923/merge-html-element-object-with-a-custom-object

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值