user3142695 user3142695 - 1 year ago 37
Javascript Question

Get variable by its name, which is stored in another variable

How can I select an array variable by its name?

This is what I'm doing so far to get the content in a dynamic way:

const lib1 = ['banana', 'apple'],
lib2 = ['audi', 'bmw'];
let index = 1;

lib1[index] // result: apple

Now I need to select the array-variable also dynamical:

let library = 'lib2',
index = 1;

library[index] // wrong - but should result 'bmw'

Answer Source

You could change the data structure a bit and access then with a key.

var lib1 = ['banana', 'apple'],
    lib2 = ['audi', 'bmw'],
    object = {lib1, lib2},
    index = 1,
    library = 'lib2';