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
  • 15,275
  • 8
  • 53
  • 104
rb-
  • 2,315
  • 29
  • 41

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,197
  • 1
  • 19
  • 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
  • 74,004
  • 20
  • 105
  • 125