0

for example I ask the user to enter an input and he enters "key" and I save the value on a variable called INPUT. Then I want to create an object with this like this.

var obj = {INPUT: "some other input"}; where INPUT = key

I know I can add more values but I need to know the key ahead of time in order to add it. Can I add a new key without knowing what it is?

polaris
  • 339
  • 2
  • 14
  • 33
  • 1
    You can do `var obj = {}; obj[Input] = "some other input";` where `var Input = "derp";` or whatever. –  May 16 '17 at 19:19

1 Answers1

5

Yes, with computed property names. Assuming INPUT is an actual variable, simply wrap it in [].

var obj = {[INPUT]: "some other input"};

The long version of doing this would be to use bracket notation when adding your keys.

var obj = {};
obj[INPUT] = "some other input";
Joseph
  • 117,725
  • 30
  • 181
  • 234