doom
1
Hello, I am trying to build a chrome extension. I am storing some data with chrome storage API. Here is the code right now I am using.
let userDetails = {...}
chrome.storage.local.set({'userDetails': JSON.stringify( userDetails )});
But I want to use a function to make the process dynamic. For example.
function setStorageValue( objectKey, objectValue ){
chrome.storage.local.set({objectKey: JSON.stringify( objectValue || {} )});
}
And it’s not working. How do I solve the problem? How do I set the object key by variable?
nazmun
2
Why not define the object first and then pass it to the storage API?
function setStorageValue( objectKey, objectValue ){
let data = {};
data[objectKey] = JSON.stringify( objectValue || {} );
chrome.storage.local.set(data);
}
In ES6 (ECMAScript 2015) you can define dynamic object key in JavaScript. You can define the object key like below.
let data = {
[objectKey]: objectValue,
}
So the final output should look like this.
function setStorageValue( objectKey, objectValue ){
chrome.storage.local.set({
[objectKey] : JSON.stringify( objectValue || {} )
});
}