Julius S. Julius S. - 1 year ago 87
Javascript Question

Passing a variable as a property name

I need to pass a variable as a property name in the following function:

var value;
chrome.storage.local.set({name: value});

I already achieved this using ES6 - object literal extensions - computed properties:

var value;
var name;
chrome.storage.local.set({[name]: value});

But according to ECMAScript 6 compatibility not all browsers support this script.

Is there a solution which can be handled by more browsers?

Answer Source

You can use bracket notation to set the property name of an object. See chrome.storage.local.set using a variable key name, chrome.storage

var value = "123";
var name = "abc";
var obj = {};
obj[name] = value;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download