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

196
Views
how can I prevent errors with nested data in an array if it is empty?

I have this example:

var data={
  city:{
    street:{
      houses:[]
    }
  }
}

alert(data.city.street.houses?.[0].person);

    var data={
      city:{
        street:{
          houses:[]
        }
      }
    }

    alert(data.city.street.houses?.[0].person);

this would show an error because it does not exist houses[0], how can I avoid having errors but in case houses[0] does exist, continue with the nesting?

doing this, I am getting errors:

enter image description here

how can I do it?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Just add another chaining operator after the array item reference:

var data = {
  city: {
    street: {
      houses: []
    }
  }
}

let res = data.city.street.houses?.[0];
res = res != undefined ? res.person : 'no value';
console.log(res);

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!