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

178
Views
Uncaught Type Error when accessing JSON data

I have the following JSON data:

const randomData = 
    [
      {
        gender: 'male',
        name: {
          title: 'Mr',
          first: 'Blake',
          last: 'Li',
        },
      },
    ];

When I attempt to access the first name property using name = randomData[0].name.first, I get the following error: Uncaught TypeError: Cannot read properties of undefined (reading 'first')

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

0

I'm assuming you are consuming an API, that would have the following JSON structure, because your mock example are just fine to do what you want.

And prob what is happening is that some of ur data doens't have value in name object.

So you would need to make a check when trying to access name.first.

ex:

const name = randomData[0].name.first || 'No name'

const name = randomData[0].name && randomData[0].name.first

about 4 years ago · Juan Pablo Isaza Report

0

I recommend you use a JSON validator every-time you get data to verify that structure you expect is correct. I built a small (21kBs) but powerful JSON validator: https://www.npmjs.com/package/great-json-validator

Validating the structure of incoming data will guarantee you won't get this type of errors.

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!