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

132
Views
How to destructure nested object that might be undefined in javascript

I have a function that returns an object like the following:

{
    data: {key1: value1, ...},
    errors: [...]
}

I can extract key1 with the following:

const { data: { key1 }} = myFunction()

However, sometimes data is undefined which causes the destructuring to fail.

I've looked at the destructuring examples and haven't been able to figure out how to pull out key1 when data might be undefined.

Is there a way to assign a default value of {} to data when performing the destructuring so that it doesn't fail?

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

0

You could take a default object.

const
    myFunction = () => ({}),
    { data: { key1 } = {} } = myFunction();

console.log(key1);

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!