Search code examples
javascriptecmascript-6destructuring

Destructuring argument with object and key from destructured object?


Is it possible to obtain a destructured variable from the object that gets passed in by using another destructured argument as the key?

var test = { 
    a: { 
        b: 'c' 
    },
    access: 'b' 
};

myFunc(test);

function myFunc( { a : { access /*???*/ } } ) {
    console.log(/*???*/);  // should output 'c'
}

working way -

function myFunc( { a, access }) {
    console.log(a[access]);  // should output 'c'
}

Solution

  • Yes, this is possible using computed property names:

    function myFunc( { access, a : { [access]: val } } ) {
        console.log(val); // does output 'c' when called with test
    }
    

    You will need to ensure that access is initialised first though, before accessing the property of a.

    I would however recommend to avoid this, it will confuse the heck out of any reader. Don't try to be clever. Your working way is also the most readable way.