I want to create an object of type {key:value}
where the key name is variable. Such object must be provided to chrome.storage.<storageType>.set(keys, function(){...})
There are a lot of related questions on SO with working answers, but I was not able to find a suitable explanation of the problem. It boils down to setting a property on a JSON object. I did this test:
var desiredKey = "123",
desiredValue = "Value for key 123",
foo;
// 1-The basic: Using a literal
console.log({ "123": desiredValue });
// 2-The problem occurs when the key name is not a literal
console.log({ desiredKey: desiredValue });
// 3-The solution is to assign a key explicitely
foo = {};
foo[desiredKey] = desiredValue;
console.log(foo);
Results:
Object { 123: "Value for key 123" } <-- Literal
Object { desiredKey: "Value for key 123" } <-- Variable (wrong)
Object { 123: "Value for key 123" } <-- Assignment (ok)
Questions:
- Why does method 2 fail? What is stored? the reference/address of
desiredKey
? - Is method 3 the simplest one? or is there a one instruction solution?