Search code examples
javascriptecmascript-6destructuring

ES2015 (ES6) sub destructuring


I have question regarding destructuring in Javascript, say for example I have this object structure:

let obj = { 
    subObj: {
        id: 123,
        otherProp: 'value'      
    }
};

Is this destructuring pattern even possible:

let { subObj: { id } } = obj

let someId = id;
let otherObj = subObj //this is not working

I would like to grab the sub object and a property within the sub object in one operation. I've had a look on this resource 2ality but cant to find an answer.


Solution

  • I would like to grab the sub object and a property within the sub object in one operation

    You can do that like this:

    let {subObj : {id}, subObj} = obj;
    //   ^^^^^^^^^^^^^  ^^^^^^
    //         \           \----- grabs subObj
    //          \---------------- grabs id
    

    The other order is fine too:

    let {subObj, subObj : {id}} = obj;
    //   ^^^^^^  ^^^^^^^^^^^^^
    //      \          \--------- grabs id
    //       \------------------- grabs subObj
    

    Example:

    let obj = {
      subObj: {
        id: 123,
        otherProp: 'value'
      }
    };
    // Grabs subObj ----vvvvvv
    let {subObj : {id}, subObj} = obj;
    //   ^^^^^^^^^^^^^---grabs id
    console.log(subObj);
    console.log(id);