Skip to content
Advertisement

Using a variable in place of an array

I have a number of arrays I’m using for my first Chrome extension. I want to use a different array for my extension depending on what a value is in a specific variable (locationVal), which is a number between 1-4. Here is the function that decides that:

if (locationVal === 1) {
arrayToUse = 'firstList';
} else if (locationVal === 2) {
    arrayToUse = 'secondList';
} else if (locationVal === 3) {
    arrayToUse = 'thirdList';
} else if (locationVal === 4) {
    arrayToUse = 'fourthList';
} else {
    console.log("setArray function error");
}
chrome.storage.local.set({arrayToUse});

The firstList, secondList, etc. are my arrays, which are declared as:

let firstList = [];
let secondList = [];
let thirdList = [];
let fourthList = [];

The main thing I’m wondering, is how will the arrayToUse variable be used as an array name in a settings such as this:

chrome.storage.local.get({arrayToUse: []}, function(items) {
  if (!chrome.runtime.error) {
    arrayToUse = items.arrayToUse;
  }
});

and

chrome.storage.local.set({arrayToUse : arrayToUse}, function() {
if (!chrome.runtime.error)....

I think that is being used as a string as-is and it is causing an issue there. If I put in one of my arrays directly, the program works fine.

Advertisement

Answer

I’d recommend using a map to store references to your arrays. This way you can access those by a string identifier, which can be the same as the variable name of a particular array. This string can then be saved to the localStorage.

Something like:

let firstList = [1, 2, 3];
let secondList = [4, 5, 6];
let map = new Map();
map.set("firstList", firstList);
map.set("secondList", secondList);

let arrayToUse = "secondList";
console.log(map.get(arrayToUse));
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement