How to access an object inside another object in a map in react

react.js is complicated sometimes, I’m trying to access an information of a state, I have an array which has one object inside, and in this object, there is another object called price, and in this last object there is one property called price too, and when I try to get this information in a map function, the code breaks, this is my map code: (the error line is in ******) the error show like this: Uncaught TypeError: Cannot read properties of undefined (reading ‘price’)

products.map((item) => {
                    return (
                        <MainContainer onMouseEnter={() => onEnter(item.id)} key={item.id}>
                            <Card>
                                <TopContainer>
                                    <p>163892</p>
                                    <h2>{item.name}</h2>
                                    <Icons>
                                        <svg clip-rule="evenodd" fill-rule=</svg>
                                        <InfoOutlinedIcon/>
                                    </Icons>
                                </TopContainer>
                                <hr/>
                                <MidContainer>
                                    <img src='https://cfarma-public.s3-sa-east-1.amazonaws.com/images/nexfar-product-default-image.jpg'/>
                                    <div>
                                        <p>Base</p>
****************************************<p>Nexfar<br/>R${item.price.price}</p>********************
                                    </div>
                                    <div></div>
                                    <div></div>
                                    <div></div>
                                    <div></div>
                                </MidContainer>
                            </Card>
                        </MainContainer>
                    );
                }) 

this image shows how the objects structure is

Thank you guys!

>Solution :

As stated in the comments,

The problem is that one or more elements in your array doesn’t have the .price.price property which would cause a type error since it doesn’t exist.

To fix this you could do item?.price?.price

The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.

see more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

Leave a Reply