I have been experimenting with assigning many values nested in an object from within the parent assignment in Object.assign. I got it to work the way I wanted it. However, I do not know how or why it is working. Why does style need to be computed before the second Object.assign will evaluate it?
var cards = Object.assign(card=document.createElement('div'),style=card.style, {
id:'cards',
innerHTML:'hello world',
[style]:[Object.assign(style,{
width:"300px",
margin:'auto',
color:'green',
height:'300px',
})]
});
var body= document.querySelector('body');
body.appendChild(cards);
That code does not do what you want, and does not work the way you think it does. Notice that you are accidentally introducing global variables, and your computed property key will be the useless and unused "[object CSSStyleDeclaration]"
. It just does have the desired effect because Object.assign(style, …)
is evaluted, but doing it in the nested object has no impact.
You should just write
var card = document.createElement('div');
Object.assign(card, {
id:'cards',
innerHTML:'hello world'
});
var style = card.style;
Object.assign(style, {
width:"300px",
margin:'auto',
color:'green',
height:'300px',
});
var body = document.querySelector('body');
body.appendChild(cards); // probably not necessary, cards already is part of the document
or possibly even simpler
var card = document.createElement('div');
card.id = 'cards';
card.innerHTML = 'hello world';
var style = card.style;
style.width = "300px";
style.margin = 'auto';
style.color = 'green';
style.height = '300px';
Maybe it helps to see what you were doing wrong when we desugar the Object.assign
s. Your code is equivalent to
_temp1 = card=document.createElement('div'); // global variable!
_temp2 = style=card.style; // global variable!
_temp3 = {
id:'cards',
innerHTML:'hello world'
};
_temp4 = style;
_temp5 = {
width:"300px",
margin:'auto',
color:'green',
height:'300px',
};
for (p in _temp5) // the Object.assign(style, {…})
_temp4[p] = _temp5[p];
_temp3[String(style)] = [_temp4]; // WTF
for (p in _temp2) // the first part of Object.assign(card, style, …)
_temp1[p] = _temp2[p]; // WTF
for (p in _temp3) // the second part of Object.assign(card, …, {…})
_temp1[p] = _temp3[p];
var cards = _temp1;
var body = document.querySelector('body');
body.appendChild(cards);