Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

183
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda