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?

2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.
2

You need a computed property name for an object literal.

{ [key]: value }
  ^^^^^           left hand side brackets, takes value of key

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.