1

I have an object that I want to initialize with dynamically named keys. I know I can do it in code like this:

obj = {};
prefix = "blah";
i = 0;
obj[prefix + i] = "whatever";
console.log( obj.blah0 );

e.g. like from here: How do I create a dynamic key to be added to a JavaScript object variable

But can this be done in an initializer?

obj = { [prefix+i]: "whatever" };

I know that doesn't work. I tried it. But is there a similar method that does work?

Community
  • 1
  • 1
Rafael Baptista
  • 11,181
  • 5
  • 39
  • 59

1 Answers1

5

You can't dynamically generate keys in object literals in the current version of JavaScript.

You can use an anonymous function as a constructor, and generate key-value pairs that way:

obj = new function() {
    var i,
        prefix;
    prefix = 'blah';
    i = 0;
    this[prefix + i] = "whatever";
};
console.log(obj.blah0); //"whatever"
zzzzBov
  • 174,988
  • 54
  • 320
  • 367