javascriptobjectecmascript-6

How to provide default values for an empty string in a destructured object


While performing object destructuring it is possible to provide default values if the key does not exist (i.e. undefinedKey).

If the (string) key does exist, it does not get overwritten (even if empty).

I'm wondering if it's possible to specify an override for an empty string while destructuring. In the example below, I would like emptyKey to print Override for empty key

const testObject = {
  emptyKey: '',
  filledKey: 'Some Initial Value',
};

const {
  emptyKey = 'Override for empty key',
  filledKey = 'Override for filled key',
  undefinedKey = 'Override for undefined key',
} = testObject;

console.log(emptyKey); //''
console.log(filledKey); //'Some Initial Value'
console.log(undefinedKey); //'Override for undefined key'


Solution

  • I'm wondering if it's possible to specify an override for an empty string while destructuring.

    No, default values are only considered if the property value is undefined. There is no way to override this behavior.


    As a workaround, you could build your own little default value handler, such as

    function defaults(obj, test, defaults) {
      return Object.keys(defaults).reduce((acc, prop) => {
        acc[prop] = test(obj[prop]) ? defaults[prop] : obj[prop];
        return acc;
      }, {});
    }
    
    const testObject = {
      emptyKey: '',
      filledKey: 'Some Initial Value',
    };
    
    const {
      emptyKey,
      filledKey,
      undefinedKey,
    } = defaults(
      testObject,
      v => v === undefined || v === '',
      {
        emptyKey: 'Override for empty key',
        filledKey: 'Override for filled key',
        undefinedKey:'Override for undefined key',
      }
    );
    
    console.log(emptyKey, filledKey, undefinedKey);

    Not quite as elegant, but flexible.