1

How can I use a variable value as an object key?

For example, when adding an object dynamically to a Collection. When I to do it like this:

addToDB(type, account) {
  Accounts.insert({type: account});
};

it doesn't work as the key can't be a variable here.

while
  • 3,602
  • 4
  • 33
  • 42
jiku
  • 283
  • 5
  • 16

1 Answers1

3

JavaScript object literal don't support dynamic keys.

Instead you can achieve the goal using :

var obj = {};
var key = "some key";
obj[key] = "test";

In your case:

addToDB(type, account) {
  var obj = {};
  obj[type] = account;
  Accounts.insert(obj);
};

More details here: Creating object with dynamic keys

Community
  • 1
  • 1
Kuba Wyrobek
  • 5,273
  • 1
  • 24
  • 26
  • Your answer is not accurate anymore. ES6 adds support for creating dynamic object keys. In case of the question above the answer would be `addToDB(type, account) { Accounts.insert({[type]: account}); };` Maybe you could improve your answer? – PaulT Jan 31 '17 at 20:25