Search code examples
javascriptecmascript-6destructuring

How to destructure and initializing missing, nested fields in the same expression?


I've been trying to figure out if nested ES6 destructuring supports this functionality. I would like to assign a as an empty object if it doesn't exist, and subsequently assign it's property name b to a scope variable b.

var {
  a = {},
  a: {
    b = 2,
  },
} = {};

VM40:4 Uncaught TypeError: Cannot destructure property `b` of 'undefined' or 'null'.
    at <anonymous>:6:5

It seems I can't really nest destructuring without assuming the objects format. The following works, but I'm looking for a more concise method where you can easily see the nested layout of the original object.

var {
  a = {},
} = {};

var {
  b = 2,
} = a;

// works as expected
// starts to look crazy when 'forking' branches that may or may not exist

Solution

  • You're looking for

    var {
      a: {
        b = 2,
      } = {},
    //  ^^^^
    } = {};
    

    The default initialiser comes after the target (which is the inner destructuring expression here). If you are looking to initialise both the variables a and b, there's not much else you can do other than having two assignments:

    var {
      a = {},
    } = {},
    {
      b = 2,
    } = a;
    

    This might look cleaner with two var declarations like you did. If you insist on doing it in one nested expression, you can do

    var {
      a = {}, // short for `a: a = {}`
      a: {
        b = 2,
      } = a, // use either `a` or another empty object as the default
    } = {};
    

    but I consider that pretty unreadable.