Sandro Vardiashvili
Sandro Vardiashvili

Reputation: 187

Can I import specific variable by variable from another file in JS?

I want to import a specific variable from another Javascript file. I now do this the standard way.

For example, I have a validation.js file where I have the following code:

export const profile = {...}

My problem is that I want to import this variable from another file by variable name:

import {profile} from "validation" //this will work

But this

let action = 'profile';

import {action} from "validation" // this will surely look for action in validation.js and not profile.

How can I import the right variable by using the action string?

Upvotes: 4

Views: 252

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370789

Import the whole namespace instead, which contains the named exports as properties of the object, and then you can just access the appropriate property on the object with []s:

import * as validation from "validation";
// ...
const action = 'profile';
const profile = validation[action];

Upvotes: 6

Related Questions