Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

82
Views
Cannot get the first element of array whereas map() works as a charm

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!