Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS destructuring. How to deal with null or undefined values

How to implement Nullable feature in es6? I need to support the source code of my previous co-worker, who used too much destructuring feature of es6. Something like this, every where:

dispatch(
    loadImports(response.items.map(({ importRecord: { ['import']: importId } }) => importId))
)

In this example, it's possible that I may get TypeError: Cannot read property 'import' of null error.

I don't want to rewrite the whole destructures to regular conditions. Or if there isn't, how to deal with them, without rewriting?

UPD:

Expected version by co-worker: https://jsbin.com/fesewiy/edit?js,console

Current version: https://jsbin.com/qirixil/edit?js,console

like image 874
xurshid29 Avatar asked Nov 20 '17 10:11

xurshid29


People also ask

How do you handle null in Destructuring?

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 . Copied!

How do you deal with undefined Destructuring?

Conclusion # The "Cannot destructure property of undefined" error occurs when we try to destructure a property from a value that is equal to undefined . To solve the error provide a fallback when destructuring the property, e.g. const {name} = undefined || {}; .

What are default values in Destructuring assignment in JavaScript?

Each destructured property can have a default value. The default value is used when the property is not present, or has value undefined . It is not used if the property has value null . The default value can be any expression.

Can we Destructure array in JavaScript?

To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element.


1 Answers

Because you are using map, you need to get some result for each item. The best solution with minimum changes will be to use only one level of destructuring and then filter the array to stay with array of values that are not falsy.

dispatch(
    loadImports(response.items
        .map(({ importRecord }) => importRecord && importRecord.import)
        .filter(v => v)
))
like image 165
Edan Chetrit Avatar answered Oct 17 '22 14:10

Edan Chetrit