xurshid29
xurshid29

Reputation: 4210

JS destructuring. How to deal with null or undefined values

How to implement Nullable feature in ? I need to support the source code of my previous co-worker, who used too much destructuring feature of . 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

Upvotes: 9

Views: 4887

Answers (2)

Edan Chetrit
Edan Chetrit

Reputation: 5081

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)
))

Upvotes: 2

guest271314
guest271314

Reputation: 1

You can set the value of the default parameter to a plain object, use OR operator to return either importId or null

arr.map(({ importRecord: { ['import']: importId } = {}}) => importId || null)

Upvotes: 0

Related Questions