0

Can I use a string as the key in a JavaScript object?

var method,
    obj;

method = function () {
  return "foo";
};

// works
obj = {
  'foo': 'bar'
};

// does not work
obj = {
  method(): 'bar'
};
Fraser
  • 13,348
  • 6
  • 50
  • 101
rb-
  • 2,166
  • 27
  • 40

3 Answers3

2

You can use square bracket syntax in javascript. This cannot be done when declaring an object literal though. You will have to do something like the following.

obj = {}; 
obj[method()] = "bar";
Ian Brindley
  • 2,061
  • 1
  • 18
  • 28
1

if you create an empty object first, then call the method as if it was the key, it will assign it how you want it to.

var method = function() {
    return 'bar';
};

var obj = {};

obj[method()] = 'bar';
jbg
  • 476
  • 2
  • 9
0

Not that way.

You CAN do this:

function doStuff() {
  return "foo";
};

var obj = {}
  ;

obj[doStuff()] = 'bar';

And on the subject of methods and subscripting...

This would appear to work, but it's a bad idea and it doesn't work how you might think:

var obj = {}
  ;

obj[doStuff] = 'bar';

What happens is doStuff will coerse as doStuff.toString() and it would sometimes behave as expected.

coolaj86
  • 69,448
  • 16
  • 99
  • 116