Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 971
Ashish Singh Rawat Avatar asked Oct 12 '25 10:10

Ashish Singh Rawat


1 Answers

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);
like image 121
Barmar Avatar answered Oct 13 '25 22:10

Barmar