Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS turn undefined value into empty string

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?

like image 829
CyberJunkie Avatar asked Dec 10 '25 06:12

CyberJunkie


1 Answers

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.

like image 124
Yury Tarabanko Avatar answered Dec 11 '25 18:12

Yury Tarabanko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!