0

What's wrong with this? How should I be doing it?

var arr = ['image', 'image.jpg'];
var obj = {arr[0]: arr[1]};
jsejcksn
  • 27,667
  • 4
  • 38
  • 62
  • 3
    [Creating object with dynamic keys](http://stackoverflow.com/questions/19837916/javascript-creating-object-with-dynamic-keys) – Jonathan Lonowski May 18 '16 at 23:27
  • @JonathanLonowski I'm confused by that because of the JQuery complication. Is the salient part the brackets? – jsejcksn May 18 '16 at 23:29
  • Object initializers expect keys to be literals – strings, numbers, or identifiers (used only for their names). In browsers/engines supporting ES2015, you can use additional brackets to define the key from a variable/expression – `var obj = { [arr[0]]: arr[1] };`. Otherwise, it'll have to be a separate statement – `var obj = {}; obj[arr[0]] = arr[1];`. – Jonathan Lonowski May 18 '16 at 23:30
  • Reference: [MDN: Object Initializer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) and [computed property names](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names) – Jonathan Lonowski May 18 '16 at 23:40
  • @JonathanLonowski Thanks. That was what I needed. Want to turn that into an answer so I can give you credit? – jsejcksn May 18 '16 at 23:45

1 Answers1

0

The problem is that expressions like arr[0] cannot be used as keys in the literal initializer notation of an object. Instead, the property must be assigned dynamically.

var arr = ['image', 'image.jpg'];
var obj = {};
obj[arr[0]] = arr[1];
GOTO 0
  • 42,323
  • 22
  • 125
  • 158