简体   繁体   中英

Can I destructure a variable where property name defined by a variable itself?

For example I have in localStorage object properties Meteor.userId and Meteor.loginToken . I can destructure them as following:

const {
      'Meteor.userId': userId,
      'Meteor.loginToken': loginToken,
    } = localStorage;

But can I define Meteor.userId and Meteor.loginToken as a variables? For example:

const METEOR_USER_ID = 'Meteor.userId';
const METEOR_LOGIN_TOKEN = 'Meteor.loginToken';

Tried to use the following code, but it doesn't work:

const {
      METEOR_USER_ID: userId,
      METEOR_LOGIN_TOKEN: loginToken,
    } = localStorage;

You need a computed property to take the key of the variable.

const {
    [METEOR_USER_ID]: userId,
    [METEOR_LOGIN_TOKEN]: loginToken,
} = localStorage;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM