从解构对象中解构对象和键的解构参数?

Destructuring argument with object and key from destructured object?

是否可以通过使用另一个解构参数作为键从传入的对象中获取解构变量?

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

myFunc(test);

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

工作方式-

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

是的,这可以使用计算的 属性 名称:

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

您需要确保先初始化 access,然后再访问 a 的 属性。

但是我建议避免这种情况,它会混淆任何 reader。不要自作聪明。你的工作方式也是最易读的方式。