Although this question is very old, there is a simple syntax in ES 6 that solves the problem. Refer to solution 2.
Problem
In your code,
{ key: testPrefs }
creates an object with a key key instead of myKey. It does not refer to the content of the variable key.
Here are two solutions to set myKey (or any string that is known in runtime only) to testPrefs in an object.
Solution 1:
Create an object first, then use the obj[key] syntax.
function storeUserPrefs() { var key = 'myKey', testPrefs = {'val': 10}; var obj = {}; obj[key] = testPrefs; // The key name is resolved dynamically to 'myKey' chrome.storage.sync.set(obj, function() { console.log('Saved', key, testPrefs); }); }
Solution 2 (ES 6):
Use the { [key]: testPrefs } syntax.
function storeUserPrefs() { var key = 'myKey', testPrefs = {'val': 10}; chrome.storage.sync.set({ [key]: testPrefs }, function() { console.log('Saved', key, testPrefs); }); }
Note when getting from storage:
Your code
chrome.storage.sync.get('myKey', function (obj) { console.log('myKey', obj); });
returns { myKey: { 'val': 10 } } instead of { 'val': 10 }. So for me, I will print obj[key] instead of obj.
{key: "something"}JS creates an object with a property named 'key', not the value of the key variable declared before. You can only use a variable on the right side of the colon. See section 'Creating a Direct Instance' here