1

I have this function:

function SaveToStore(thisObjName) {
  var thisObj = $('#'+thisObjName);
  chrome.storage.sync.set({
    "cbSO" : thisObj.is(':checked')
  });
}

I would like to use the argument thisObjName, which contains "cbSO", as the key (property name) in the object I'm passing into chrome.storage.sync.set:

function SaveToStore(thisObjName) {
  var thisObj = $('#'+thisObjName);
  chrome.storage.sync.set({
    thisObjName : thisObj.is(':checked')
  });
}

But that's creating a property with the name thisObjName, not cbSO. How do I use the value of the argument as the key?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Zuyas
  • 182
  • 1
  • 1
  • 17
  • We _really_ need a canonical question for this. – Xan Jan 30 '15 at 19:12
  • @Xan: This question was written fairly generically, so I've genericized it further; it can be the canonical. Sure, it's not the first time this has been asked, but that's true for lots of now-canonical questions, and this one was fairly clean to start with, so... :-) – T.J. Crowder Jan 31 '15 at 12:56
  • 1
    @Xan: I think there already is one, at least I always use it as a duplicate target. The other two questions with good answers are linked in the comments [there](https://stackoverflow.com/questions/2274242/using-a-variable-for-a-javascript-object-key). – Bergi Jan 31 '15 at 14:00
  • @T.J.Crowder: If you want to make a really clean canonical question, please strip it of all the jquery and chrome stuff and focus on the object literal. I'd suggest however that we use either [this highest-voted](http://stackoverflow.com/q/11508463/1048572) or [this most-frequently-linked](http://stackoverflow.com/q/2274242/1048572) one to start with (and ask a mod to make them community-wiki). – Bergi Jan 31 '15 at 14:03

1 Answers1

3

There are two answers to this question:

  • The answer for ECMAScript5 (ES5) and below

  • The answer for ECMAScript6 (ES6) and up

The answer for ECMAScript5 (ES5) and below

You can't do it with a property initializer, the part before the : is always used literally, it's not an expression that gets evaluated.

To create a property with a name from a variable, you have to create the object separately, then set the property using brackets notation (and then pass the object to the function):

function SaveToStore(thisObjName) {
  var thisObj = $('#'+thisObjName), args = {};
  args[thisObjName] = thisObj.is(':checked');
  chrome.storage.sync.set(args);
}

The answer for ECMAScript6 (ES6) and up

You can do that with a computed property name in the property initializer. It looks like this:

function SaveToStore(thisObjName) {
  var thisObj = $('#'+thisObjName);
  chrome.storage.sync.set({
      [thisObjName]: thisObj.is(':checked') // ES6 syntax! Not currently widespread
  });
}

Note the [] around the thisObjName on the left-hand side of the : — those indicate that what's inside is an expression, not a literal.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875