1

var arr = [ 'key', 'value' ];
console.log(arr);

var obj = { arr[0] : arr[1] };
console.log(obj);

I'm getting an error doing this array to object conversion. However, this isn't a problem:

var arr = [ 'key', 'value' ];
var key = arr[0];
var value = arr[1];

var obj = { key : value };
console.log(obj);

Why doesn't the array substitution work? What am I doing wrong?

Isaac
  • 12,042
  • 16
  • 52
  • 116
eozzy
  • 66,048
  • 104
  • 272
  • 428
  • 6
    Possible duplicate of [How to use a variable for a key in a JavaScript object literal?](https://stackoverflow.com/questions/2274242/how-to-use-a-variable-for-a-key-in-a-javascript-object-literal) – Jacob Goh Jun 20 '18 at 03:01
  • 1
    The second version is equally problematic. The property's key will be `key`, not the value you get from the array. Should be `var obj = { [key] : value };` – Robby Cornelissen Jun 20 '18 at 03:05

2 Answers2

8

var arr = [ 'key', 'value' ];
console.log(arr);

var obj = { [arr[0]] : arr[1] };
console.log(obj);

I think the problem is in the key part. have a look how i did it.

Inus Saha
  • 1,918
  • 11
  • 17
  • this is a very confusing syntax. Would you mind changing your answer so that the code is a bit more declarative? In my opinion, something like: var obj = {}; obj[arr[0]] = arr[1]; Would be easier to understand. – Hassaanz Jun 20 '18 at 03:08
  • 2
    the person who asked this question has very good reputation. so i posted this answer keeping in mind that he must be an expert. but sure your way is also perfect. meanwhile someone has posted a link of possible duplicate where your answer is also mentioned. – Inus Saha Jun 20 '18 at 03:17
  • Thanks for the explanation on your answer :) – Hassaanz Jun 20 '18 at 10:51
2

You need a computed property name for an object literal.

{ [key]: value }
  ^^^^^           left hand side brackets, takes value of key
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392