JS destructuring. How to deal with null or undefined values

Viewed 4118

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

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

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