简体   繁体   中英

Is it possible to combine optional chaining with arrays and map (in Javascript)?

I recently learned about optional chaining in Javascript and have been making use of it in a React/NodeJS project. Works great.

I noticed I have been using it with arrays map , even without thinking about it much -- it seemed a natural use (here items is an array, or possibly undefined )

        {items?.map(postListItem => ....

That is, it will map if items exists, but not if items is undefined , but would avoid any run-time errors if I were to call map on undefined

Nonetheless I don't know if this is an acceptable use or whether I'm mis-using optional chaining. I searched for an answer but as of yet haven't been able to find one, which makes me suspect I'm mis-using it. Any info much appreciated!

See answer here regarding the typescript usage. You need a period for array null safe Optional Chaining.

    this.mostRecentMfaAttempt = this.verificationsAttempts?.content?.[0]

How to use optional chaining with array in Typescript?

Using optional chaining operator for object property access

If the chaining fails, the expression will evaluate to undefined .

When a child is evaluated to undefined , it just won't render .

Conditional rendering is already quite a common strategy. Previously, when you have something that may be an array or may be undefined , and you want to map if there's an array, you would have had to do something like:

{ items && items.map( ...

This works because, if items is undefined , the whole expression will be evaluated to undefined , and no rendering will happen, and no errors will be thrown.

Using optional chaining works exactly the same way, except that it's more concise. So yes, this is a perfectly valid thing to do.

Optional chaining is stage 4 , so you can count on it working reliably.

Arrays are objects . But optional chaining isn't only for objects - it can work for anything which may have a property or method. Eg const bar = foo?.toFixed(2) will work fine if foo is null , undefined , or a number (numbers have a toFixed method).

The optional chaining way to your problem is:

{items?.map?.(postListItem => ....)

Read more here: MDN Web Docs: Optional chaining

To get data from the MongoDB database by filtering use below system.

cars.filter(car => car.email === user.email)?.map(car => {
    return (
        <tr key={car._id}>
            <td>{car.userName}</td>
            <td className=''>{car.email}</td>
            <td>{car.name}</td>
            <td><img src={car.img} alt="" /></td>
        </tr>
    )
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM