1

I have a requirement where I have to take a couple of values from a nested object which when not available, should be taken from a default object. For example consider the following object:

const objToDestructure={
   someVal:3,
   anotherVal:4,
   outerObj:{}
}

If I want to take two field field1 and field2 from outerObj then what I was able to do was

const { someVal,anotherVal,outerObj = {field1:22,field2:33}}=objToDestructure;
const {field1,field2}=outerObj;

Is there anyway this can be shortened even more? I tried to do the following:

const { someVal,anotherVal,outerObj:{field1,field2} = {field1:22,field2:33}}=objToDestructure;

But I got both the values as undefined. Is there any reason why this won't work but the individual assignment does?

1
  • 1
    just as a suggestion, shorter does not imply more readable. Sometimes destructuring nested objects can be a bit trickier to read for the rest of the devs Commented Dec 16, 2019 at 20:18

1 Answer 1

1

Because outerObj exists (it's not undefined) in objToDestructure, setting a default for it won't help in this case. Since it's an object, you can destructure field1 and field2 individually, and set a default for each of them:

Set a default empty object, and add a default value for each field:

const { outerObj:{ field1 = 22, field2 = 33} = {}} = objToDestructure;

Example:

const objToDestructure={
   someVal:3,
   anotherVal:4,
   outerObj:{}
}

const { outerObj: { field1 = 22, field2 = 33} = {}} = objToDestructure

console.log(field1, field2)

Sign up to request clarification or add additional context in comments.

4 Comments

I know that for separate values it can be done. is there anyway that this can done in a shortened way where we give the defaults as an object instead of specifying separately each field?
option 2 is not visible
Updated the answer.
in my attempt to make the question smaller i left out some details. terribly sorry. can you take a look now please

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.