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

134
Visualizações
Nested map function resulting in a TypeError after finishing execution

code:

window.reddit.comments("uq0mzi").sort('hot').fetch(function(res) {
 res[1].data.children.flatMap((item) => {
      console.log(item.data.body)
      item.data.replies.data.children.map(y => (y.data.body === undefined ? "" : console.log(" >>>"+y.data.body)))
 })})

what I'm trying: I'm using the reddit API wrapper to get comments and their replies of a post. first map prints out the top level comments, while the second map is supposed to print out the replies to those comments

where its going wrong: the code works, but after printing everything, I'm getting a type error saying:

Uncaught TypeError: Cannot read properties of undefined (reading 'children')

how do I fix it?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

My favorite solution is to use getSafe function to avoid undefined errors.

If a nested value is undefined, a default value will be returned instead of undefined

const getSafe = (fn, defaultVal) => {
    try {
        if (fn() === undefined || fn() === null) {
            return defaultVal
        } else {
            return fn();
        }

    } catch (e) {
        return defaultVal;
    }
}

window.reddit.comments("uq0mzi").sort('hot').fetch(function(res) {
    res[1].data.children.flatMap((item) => {
         console.log(item.data.body)
         getSafe(()=>item.data.replies.data.children, []).map(y => (y.data.body === undefined ? "" : console.log(" >>>"+y.data.body)))
    })})
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