4

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?

0

1 Answer 1

6

You could take a default object.

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

console.log(key1);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.