Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destructure nested object that might be undefined in javascript [duplicate]

Tags:

javascript

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?

like image 666
Paymahn Moghadasian Avatar asked Oct 14 '25 14:10

Paymahn Moghadasian


1 Answers

You could take a default object.

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

console.log(key1);
like image 78
Nina Scholz Avatar answered Oct 17 '25 04:10

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!