Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destructure nested object with null value using default value

When trying to destructure a nested object which could be null, the default value is not being used.

I have accomplished this by destructuring in multiple stages, but would rather do it in a single stage if possible.

const obj = { a: null };
const { a: { b, c } = {} } = obj;

This results in error:
Cannot destructure property 'b' of 'undefined' or 'null'

I would expect b and c to be undefined

like image 821
ut9081 Avatar asked May 13 '19 08:05

ut9081


People also ask

Can you Destructure a nested object?

Destructuring nested objectsIf we need to access an employee's info we can destructure as many levels as it takes to get to our employee object's properties. const { engineers: { 1: { id, name, occupation, }, }, } = employees; Now we have access to all of the second employee object's properties.

How do you Destructure a null object?

Use the logical OR operator to destructure from a nullable object in TypeScript, e.g. const { name, age } = obj || ({} as Person) . The logical OR operator is used to provide a fallback in case the object has a value of null or undefined .

How will you set a default value while Destructuring an array?

In Arrays: In Arrays, values of corresponding elements get stored in the variables. Example 1: In order to give default values in arrays when applying the destructuring concept in arrays, we need to initialize values with some value. In this way the default values will be assigned to the variables.


1 Answers

For the default value to be used, the value which you are destructuring must be undefined.

const obj = { a: undefined };
const { a: { b, c } = {} } = obj;

console.log(b, c)
like image 60
Nina Scholz Avatar answered Oct 08 '22 08:10

Nina Scholz