Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!