2

I have a function that returns an object like the following:

{
    data: {key1: value1, ...},
    errors: [...]
}

I can extract key1 with the following:

const { data: { key1 }} = myFunction()

However, sometimes data is undefined which causes the destructuring to fail.

I've looked at the destructuring examples and haven't been able to figure out how to pull out key1 when data might be undefined.

Is there a way to assign a default value of {} to data when performing the destructuring so that it doesn't fail?

Paymahn Moghadasian
  • 9,301
  • 13
  • 56
  • 94

1 Answers1

4

You could take a default object.

const
    myFunction = () => ({}),
    { data: { key1 } = {} } = myFunction();

console.log(key1);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392