Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

72
Views
ES6 Dynamically Reference Import

Say I'm importing a few objects that all have the same method. How can I dynamically reference them, say by strings.

For example,

import { Foo } from 'path/to/foo';
import { Bar } from 'path/to/bar';
import { Baz } from 'path/to/baz';

const things = ['Foo', 'Bar', 'Baz'];

things.forEach(thing => {
  thing.doSomething();
});
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

If it has to be strings you can do this:

import { Foo } from 'path/to/foo';
import { Bar } from 'path/to/bar';
import { Baz } from 'path/to/baz';

const things = {
'Foo': Foo, 'Bar': Bar, 'Baz': Baz
};

Object.keys(things).forEach(key => {
  things[key].doSomething();
});

If it doesn't have to be strings, you can simply create an array of your imported Objects

import { Foo } from 'path/to/foo';
import { Bar } from 'path/to/bar';
import { Baz } from 'path/to/baz';

const things = [Foo, Bar, Baz];

things.forEach(thing => {
 thing.doSomething();
});
about 4 years ago · Juan Pablo Isaza Report

0

Just don't use string , use as you have imported like this:

import { Foo } from 'path/to/foo';
import { Bar } from 'path/to/bar';
import { Baz } from 'path/to/baz';

const things = [Foo, Bar, Baz];

things.forEach(thing => {
 thing.doSomething();
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!