Anatoly
Anatoly

Reputation: 5241

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;

Upvotes: 1

Views: 71

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386728

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

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

Upvotes: 4

Related Questions