I'm using the Object.assign() to copy values to an object:
const { one, two, three } = attributes;
return Object.assign( props, {
"data-one": one,
"data-two": two,
"data-three": three
} );
If the value of a property is empty it returns undefined. I want it to return an empty string or ideally not copy any empty properties.
I tried this:
const { one, two, three } = attributes;
var oneValue = one ? one : "";
var twoValue = two ? two : "";
var threeValue = three ? three : "";
return Object.assign( props, {
"data-one": oneValue,
"data-two": twoValue,
"data-three": threeValue
} );
It works by sending empty values instead of undefined but doesn't seem very fancy. Is there a better way to handle this?
You could define default values when using destructuring.
const attributes = { one: 'one' };
const { one = '', two = '', three = '' } = attributes;
const props = {}
console.log(Object.assign( props, {
"data-one": one,
"data-two": two,
"data-three": three
}));
Finally, if you have lots of common behavour you could just name properties you want to copy and write a loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With