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

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

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 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