2

I need to figure out how to create a dynamic key string for an object. This expression makes JavaScript complain.

return {$(this).val(): true};      // returns an object e.g. {2: true}

What am I doing wrong?

silkfire
  • 24,585
  • 15
  • 82
  • 105

2 Answers2

5

You have to create the object, then use bracket notation for the dynamic key

var obj = {};
var val = $(this).val();

obj[val] = true;

return obj;

or a completely unnecessary one-liner

return (function(o,e) {o[e.value]=true; return o;})({}, this);
adeneo
  • 312,895
  • 29
  • 395
  • 388
1

The JavaScript object literal syntax {x: y} specifies that x will be a (possibly) quoteless string, and y any value. You can't use this syntax for dynamic keys.

Use this instead:

var foo = {};
foo[$(this).val()] = true;
return foo;
Amadan
  • 191,408
  • 23
  • 240
  • 301