0

Edit

My question is different than the duplicate, because I'm not asking why something works and something else doesn't, I'm asking how to do something. While both questions have the same answer doesn't mean they are the same.


I am trying to create an object for a Google Chrome Extension using the following function:

     function set(key, value) {
          chrome.storage.local.set({`${key}`:value}, function() {
          console.log('Value is set to ' + value);
        });
    }

For some reason, this doesn't work.

Some things that I have already tried are shown below:

function set(key, value) {
          chrome.storage.local.set({[`${key}`]=value, function() {
          console.log('Value is set to ' + value);
        });
    }
function set(key, value) {
          chrome.storage.local.set({key:value}, function() {
          console.log('Value is set to ' + value);
        });
    }
function set(key, value) {
          chrome.storage.local.set({"'"+key+"'":value}, function() {
          console.log('Value is set to ' + value);
        });
    }

None of which seem to work.

What I would like to happen is to be able to set any key to any value inside of the chrome extension local memory using a function.

Expected Code:

set('testKey', 'testValue')

Expected Output:

Value is set to testValue

Actual Output:

Uncaught SyntaxError: Unexpected template string
WhiteFire356
  • 92
  • 2
  • 8
  • 2
    JS syntax for [computed property names](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names) is `{[expression]: value}`. – ASDFGerte Oct 16 '19 at 23:45
  • 1
    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) – ASDFGerte Oct 16 '19 at 23:49

1 Answers1

2

You don't even need template syntax. Just use square bracket notation:

function set(key, value) {
    chrome.storage.local.set({ [key]: value }, function() {
        console.log('Value is set to ' + value);
    });
}
B. Fleming
  • 7,170
  • 1
  • 18
  • 36