user5508297 user5508297 - 4 months ago 17
Javascript Question

How to set variable key and value in Google Chrome local storage sync?

I'm using Chrome's version of localStorage (

) and I want to use a variable key and value when setting what data to store with it.

I'd like to be able to do something like this:

chrome.storage.sync.set({ user: id }, callback);


where the user and id are dynamically generated.

This:

var user = "Bob";
var id = "81256309";

chrome.storage.sync.set({ user: id }, callback);


doesn't work because it doesn't interpret
user
and
id
as their underlying string values and, as a result, syncs to Chrome with this object:
{ user: id }
.

I know how to do this with normal JavaScript objects but the method in that thread won't work in this case because I don't have control over the storage.sync object of my Google account.

Answer

See Computed property names in ES6, you could use

chrome.storage.sync.set({ [user]: id }, callback);