0

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?
mins
  • 6,478
  • 12
  • 56
  • 75
  • 1
    *"It boils down to setting a property on a JSON object."* No, it doesn't, because this has nothing whatsoever to do with JSON. JSON is a *textual notation* for data exchange. [(More)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. What you want to do is create an object with a property whose name comes from a variable. – T.J. Crowder Oct 08 '16 at 13:02
  • @T.J.Crowder: Thanks for the explanation, that was obviously not clear to me. – mins Oct 08 '16 at 13:04

1 Answers1

2

Method 4

Computed property:

Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed as the property name. This is symmetrical to the bracket notation of the property accessor syntax, which you might have used to read and set properties already.

var desiredKey = "123",
    desiredValue = "Value for key 123",
    foo = { [desiredKey]: desiredValue };

console.log(foo);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 3
    Surely you knew this was a duplicate question. – T.J. Crowder Oct 08 '16 at 13:03
  • The result is `"123": "Value for key 123"`, that doesn't seem to be the same than `123: "Value for key 123"`, but that may be a difference between a browser console and the site renderer. Also I'm looking for the explanation. – mins Oct 08 '16 at 13:07
  • keys of objects are always strings. the console.log ma yrender different, because it is not part of ecma script. – Nina Scholz Oct 08 '16 at 16:25