Skip to content Skip to sidebar Skip to footer

How Do I Use A Variable For A Property Name In An Object Initializer/literal?

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

Solution 1:

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.

Post a Comment for "How Do I Use A Variable For A Property Name In An Object Initializer/literal?"