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
  • 22,873
  • 14
  • 77
  • 98

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
  • 303,455
  • 27
  • 380
  • 377
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
  • 179,482
  • 20
  • 216
  • 275