1

I'm using Chrome's version of localStorage (chrome.storage.sync) 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.

Community
  • 1
  • 1
user5508297
  • 805
  • 2
  • 9
  • 24
  • var obj = {}; obj[user] = id; chrome.storage.sync.set(obj,callback) – kzahel Aug 05 '16 at 01:42
  • @kzahel thanks for the quick reply. How would I later retrieve that with chrome.storage.sync.get ? – user5508297 Aug 05 '16 at 01:51
  • @kzahel unfortunately, I don't think that your method works with multiple key value pairs because if I do `var obj = {}; obj[user] = id; chrome.storage.sync.set(obj,callback)` and then `var obj = {}; obj[user2] = id2; chrome.storage.sync.set(obj,callback)` the first obj gets overwritten. – user5508297 Aug 05 '16 at 01:58
  • @kzahel I suppose you could rename obj to obj + some randomly generated id but then there's the problem of referencing that when you want to get the data later – user5508297 Aug 05 '16 at 01:59
  • @kzahel creating multiple KV pairs in the same `obj` and accessing it with the `chrome.storage.sync.get` `items.obj[user]` is another possibility but that means that each get request returns all the data, which is not ideal because it would severely limit how much data you can store – user5508297 Aug 05 '16 at 02:08
  • Use indexeddb if you want to store tons of stuff? – kzahel Aug 05 '16 at 02:13
  • @kzahel the 102,400 bytes quota for `chrome.storage.sync` is perfect for my purposes. The problem is that if I use one `obj` to store all my KV pairs I will, because it's a single item, be limited to a 8,192 bytes quota. https://developer.chrome.com/extensions/storage#property-sync – user5508297 Aug 05 '16 at 02:20
  • You should re-state your question because it is not clear what you are trying to do, and why. – kzahel Aug 05 '16 at 13:06

1 Answers1

4

See Computed property names in ES6, you could use

chrome.storage.sync.set({ [user]: id }, callback);
Haibara Ai
  • 10,703
  • 2
  • 31
  • 47