0

I have read several other posts describing dynamic variables, why not to use eval, and how to instead use objects, but I have been unable to apply this to chrome.storage.sync.

Today I do the following to save an array of data to sync storage:

...
// Update the database in the user's storage
chrome.storage.sync.set({ SEARCH_DB: LOCAL_DB }, function () {
    // Overwrite Search DB in the user's storage with the LOCAL_DB array;
});
...

Then I retrieve the database from storage with:

...
chrome.storage.sync.get({ SEARCH_DB: [] }, function (data) {
    if (data.SEARCH_DB.length > 0) {
        var LOCAL_DB = [];
        LOCAL_DB = data.SEARCH_DB.concat();
});
...

This all works fine, the problem is that instead of storing to "SEARCH_DB", I want the user to be able to input "USER'S_DB_NAME" and then be able to store that variable in sync:

...
// Update the database in the user's storage
chrome.storage.sync.set({ "USER'S_DB_NAME": LOCAL_DB }, function () {
    // Overwrite Search DB in the user's storage with the LOCAL_DB array;
});
...

And later retrieve:

...
chrome.storage.sync.get({ "USER'S_DB_NAME": [] }, function (data) {
   if (data."USER'S_DB_NAME".length > 0) {
       var LOCAL_DB = [];
       LOCAL_DB = data."USER'S_DB_NAME".concat();
});
...

Could someone help me with the code for how I can create the variable to store and retrieve with sync?

Thanks! Jon

  • Possible duplicate of [How to use a variable for a key in a JavaScript object literal?](https://stackoverflow.com/questions/2274242/how-to-use-a-variable-for-a-key-in-a-javascript-object-literal) – wOxxOm Aug 18 '19 at 03:02
  • Maybe I misunderstood the problem. Sounds like all you need is square brackets: `data["USER'S_DB_NAME"]` – wOxxOm Aug 19 '19 at 04:02
  • I think so, but I don't see how to then use it with sync. For instance, assume there is an array in sync storage with the key name "USER_INPUT". So I have: ... var INPUT = "USER_INPUT"; .... Then I have been unable to get this to work to store that sync variable in my LOCAL_DB variable. I am trying to do something like this: ... chrome.storage.sync.get({ [INPUT]: [] }, function (data) { if (data.[INPUT].length > 0) { LOCAL_DB = data.[INPUT].concat(): } This clearly doesn't work and I've been unable to find the solution. Thank you! – Jon Pointer Aug 19 '19 at 04:20
  • @wOxxOm - I apologize for being so vague - and thank you for your help. My error was that once I had chrome.storage.sync.get({ [INPUT]: [] }, function (data) { , I was accessing it with data.[INPUT] where I needed to use data[INPUT], without the period. All is working as desired now. Thanks again for your help! – Jon Pointer Aug 20 '19 at 04:13

0 Answers0