Cannot get the first element of array whereas map() works as a charm Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Cannot get the first element of array whereas map() works as a charm without wasting too much if your time.

The question is published on by Tutorial Guruji team.

In a React component want to print out the a value of an object (“name”) which is the first element in the array:

"production_countries": [
  {
    "iso_3166_1": "US",
    "name": "United States of America"
  }
]

This code collapses the app with error TypeError: Cannot read properties of undefined (reading 'name'):

<p>
  {
    movie.production_countries &&
    movie.production_countries[0].name
  }
</p>

However, if I replace the code above with a .map() everything works as a charm.

<p>
  {movie.production_countries &&
    movie.production_countries?.map((country, i) => (
      <span key={i}>
        {country.name}
      </span>
    ))}
</p>

How can I get the first element of array? Thanks

Answer

production_countries could be an empty array, in which case [0] will return undefined, using ? for early return should work:

{
  movie.production_countries &&
  movie.production_countries[0]?.name
}
We are here to answer your question about Cannot get the first element of array whereas map() works as a charm - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji