0

This is the default behavior of computed properties in JS:

const yourName = 'John';

const resultObject = {
    [yourName]: 'Glad you're here, let's celebrate!'
}

The resultObject will be computed to this:

console.log(resultObject)

{
   John: 'Glad you\'re here, let\'s celebrate!'
}

NOW... what will happen if yourName is undefined?

const yourName = undefined;
const resultObject = {
    [yourName]: 'Glad you\'re here, let\'s celebrate!'
}

console.log(resultObject)

{
   undefined: 'Glad you\'re here, let\'s celebrate!'
}

QUESTION:

Is there a way to omit the undefined computed property in the resulting object?

In other words, I'd like resultObject to be:

console.log(resultObject)

{/** void */}
paroxyzm
  • 1,422
  • 2
  • 13
  • 29
  • Maybe just `delete resultObject.undefined` :) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete – micnil May 23 '21 at 09:04
  • 2
    Either add the property procedurally after checking the value or use the spread property trick shown in the duplicates. – Felix Kling May 23 '21 at 09:08

0 Answers0