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
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