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

137
Visualizações
Ignore TypeError during For Loop

I'm trying to figure out how to "ignore" TypeErrors during a For Loop, but I would like to pass an empty string value to my variable when I do come across a TypeError or a property that does not exist. I have tried some try/catch with TypeError, but I'm not quite sure what to do with the catch. Any help is appreciated...

My obj

theObj = [ 
    {
        name:"Billy",
        age:"30",
        level:"10"
    },
    {
        name:"Jimbo",
        age:"25",
        level:"8"
    },
    {
        name:"Ralph",
        age:"37"
    },
    {
        name:"Rita",
        age:"23",
        level:"3"
    }
]

Loop

for (var i = 0; i < theObj.length; i++) {
    const levels = theObj[i]['level']
    console.log(levels)
}

console

10
8
undefined
3

What I would like to see

10
8

3

OR

10
8
Null or some other value like DNE, N/A
3
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

No problem

for (var i = 0; i < theObj.length; i++) {
    const levels = theObj[i]['level']
    console.log(levels ? levels : "")
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Try theObj[i]?.level, like:

const theObj = [ 
    {
        name:"Billy",
        age:"30",
        level:"10"
    },
    {
        name:"Jimbo",
        age:"25",
        level:"8"
    },
    {
        name:"Ralph",
        age:"37"
    },
    {
        name:"Rita",
        age:"23",
        level:"3"
    }
];

for (let i = 0; i < theObj.length; i++) {
    const levels = theObj[i]?.level;
    console.log(levels)
}

about 4 years ago · Juan Pablo Isaza Relatório

0

you should try this

const levels = theObj?.[i]?.['level'] || ""

?. make sure that the parent is defined and if not it will return undefined

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