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

192
Views
Destructuring multilevel and and assigning default value to a first level object

I am trying to destructure the a response from the API. response looks something like below. Only a and b will be used in the program.

response = {
   data: {
       someData: {
    a:1,
    b:2
    }

   }
}

destructured const {data: { someData: { a,b } } } = response

Now if data doesn't exist in the response, there are chances that app might break. I want set default value to data and someData. Is there a way to set the default value?

Tried : but throwing lint error as unexpected token

const {data= {}: { someData = {}: { a,b } } } = response

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

0

The default value goes at the end, not immediately after the variable.

And it needs to have the someData: nested object to provide the default there.

const response = {};

const {data: {someData: { a,b } } = {someData: {a:0, b:0}} } = response;

console.log(a, b);

about 4 years ago · Juan Pablo Isaza Report

0

You need to provide the default values as shown below:

const {data: { someData: { a, b } = {} } = {} } = response;

This example on MDN docs shows that the default value should be at the end, not immediately after the property name.

If the unpacked property is undefined, then the default value will be used as a target for the nested destructuring.

Example:

const response = {
  data: {}
};

const {data: { someData: { a, b } = {} } = {} } = response;

console.log(a, b);

Another option is to use optional chaining which, in my opinion, is a better approach here for code readability:

response?.data?.someData?.a
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!