Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda