Search code examples
javascriptobjectecmascript-6javascript-objectsdestructuring

Destructuring with default objects for nested object


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?


Solution

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