4

When destructuring objects, I sometimes run into the issue of not knowing whether or not keys exist, and then trying to pull values from them. This obviously errors, since they are undefined. For example:

Expecting something like this:

{ user: { name: { first: 'Trey', last: 'Hakanson' } } }

But I actually get this:

{ user: {} }

and attempting to destructure like this errors:

const { user: { name: { first: firstName, last: lastName } } } = data

is there any way to assign a default value earlier in the deconstruction? Such as assigning name = { first: 'Hello', last: 'World' } if the name key doesn't exist?

Barmar
  • 741,623
  • 53
  • 500
  • 612
treyhakanson
  • 4,611
  • 2
  • 16
  • 33

2 Answers2

9
const { user: { name: { first: firstName = 'firstName', last: lastName = 'lastName' } = {} } = {} } = data
Mayday
  • 4,680
  • 5
  • 24
  • 58
  • This guards against `name` being `undefined`, but still errors if `name` is `null` right? Any way to protect against `name` being either `undefined` or `null`? – Alan Hamlett Oct 04 '17 at 22:12
  • Don't think so, null is actually a value. Undefined just means it has not been defined that value – Mayday Oct 05 '17 at 07:10
-1

You can assign default values if the value is falsy value or undefined in your case. In javascript the default values can be assigned by using the || operator.

If the first operand is falsy (false, null, undefined, "",0) then it returns the second operand. Otherwise, it returns the first operand. This provides a convenient way to specify default values

var myDefaultName = name || { first: 'Hello', last: 'World' }
Abhinav Galodha
  • 9,293
  • 2
  • 31
  • 41
  • Thanks for the answer! I'm currently using this solution, I was looking for a solution using only es6 deconstruction though – treyhakanson Dec 15 '16 at 19:07