Julius S. Julius S. - 26 days ago 5
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

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;
chrome.storage.local.set(obj);