JavaScript 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?

Answer:1

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
}));
Answer:2

I have a problem I am sitting on for the past few days. I want to write an optimal (in JS) program for verifying if a number is a Palindrome. My current approach: function isPalidrom2(pali){ ...

I have a problem I am sitting on for the past few days. I want to write an optimal (in JS) program for verifying if a number is a Palindrome. My current approach: function isPalidrom2(pali){ ...

I have an web project where I'd like to animate the opacity of five colored divs causing them to "blink" in sequence, and the user would then click on them in the same order (like Simon says). The ...

I have an web project where I'd like to animate the opacity of five colored divs causing them to "blink" in sequence, and the user would then click on them in the same order (like Simon says). The ...

so I have a time-stamp function in a javascript file that return a date that look like MM/DD/YY I would like tom import what the function return into another script ( node.js) and display it whenever ...

so I have a time-stamp function in a javascript file that return a date that look like MM/DD/YY I would like tom import what the function return into another script ( node.js) and display it whenever ...

I need to merge a Map instance w/ an object. This didn't work: > map = new Map([ ['foo', 1] ]) Map { 'foo' => 1 } > Object.assign({}, map) {} Looks like Object.assign doesn't like maps. Is ...

I need to merge a Map instance w/ an object. This didn't work: > map = new Map([ ['foo', 1] ]) Map { 'foo' => 1 } > Object.assign({}, map) {} Looks like Object.assign doesn't like maps. Is ...