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();
});
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();
});
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();
});