0

I am trying to create a javascript object with two array indexes, but it does not seem possible. Why is that? For example:

var arr = ["name","john"];
var obj = {arr[0]:arr[1]}

3 Answers 3

4

Computed property names need brackets [myPropName]

var arr = ["name","john"]
var obj = {[arr[0]]:arr[1]}

obj.name // 'john'
Sign up to request clarification or add additional context in comments.

1 Comment

Good answer. I forgot about the brackets with my answer. Deleted it since this is the correct answer.
0

You can also do Object.assign,

var arr = ["name","john"];
var obj = {};
var newObj = Object.assign(obj, {[arr[0]]: arr[1]});
console.log(newObj);

Comments

0

If you use arr[0] then js will understand that the property name is arr[0] not "name", so you need [arr[0]] for it to interpret as "name" var obj = {[arr[0]]:arr[1]}

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.